• Places
    • Home
    • Graphs
    • Prefixes
  • Admin
    • Users
    • Settings
    • Plugins
    • Statistics
  • CPACK
    • Home
    • List packs
    • Submit pack
  • Repository
    • Load local file
    • Load from HTTP
    • Load from library
    • Remove triples
    • Clear repository
  • Query
    • YASGUI SPARQL Editor
    • Simple Form
    • SWISH Prolog shell
  • Help
    • Documentation
    • Tutorial
    • Roadmap
    • HTTP Services
  • Login

3.4 Cryptographically secure random numbers
All Application Manual Name SummaryHelp

  • Documentation
    • Reference manual
    • Packages
      • SWI-Prolog SSL Interface
        • library(crypto): Cryptography and authentication library
          • Cryptographically secure random numbers
            • crypto_n_random_bytes/2
Availability::- use_module(library(crypto)).(can be autoloaded)
Source[det]crypto_n_random_bytes(+N, -Bytes)
Bytes is unified with a list of N cryptographically secure pseudo-random bytes. Each byte is an integer between 0 and 255. If the internal pseudo-random number generator (PRNG) has not been seeded with enough entropy to ensure an unpredictable byte sequence, an exception is thrown.

One way to relate such a list of bytes to an integer is to use CLP(FD) constraints as follows:

:- use_module(library(clpfd)).

bytes_integer(Bs, N) :-
        foldl(pow, Bs, 0-0, N-_).

pow(B, N0-I0, N-I) :-
        B in 0..255,
        N #= N0 + B*256^I0,
        I #= I0 + 1.

With this definition, you can generate a random 256-bit integer from a list of 32 random bytes:

?- crypto_n_random_bytes(32, Bs),
   bytes_integer(Bs, I).
Bs = [98, 9, 35, 100, 126, 174, 48, 176, 246|...],
I = 109798276762338328820827...(53 digits omitted).

The above relation also works in the other direction, letting you translate an integer to a list of bytes. In addition, you can use hex_bytes/2 to convert bytes to tokens that can be easily exchanged in your applications. This also works if you have compiled SWI-Prolog without support for large integers.

ClioPatria (version V3.1.1-51-ga0b30a5)