/usr/lib/swipl/library/ext/ssl/crypto.pl
All Application Manual Name SummaryHelp

  • ext
    • ssl
      • ssl.pl -- Secure Socket Layer (SSL) library
      • crypto.pl -- Cryptography and authentication library
        • crypto_n_random_bytes/2
        • crypto_data_hash/3
        • crypto_file_hash/3
        • crypto_context_new/2
        • crypto_data_context/3
        • crypto_context_hash/2
        • crypto_open_hash_stream/3
        • crypto_stream_hash/2
        • crypto_password_hash/2
        • crypto_password_hash/3
        • crypto_data_hkdf/4
        • ecdsa_sign/4
        • ecdsa_verify/4
        • hex_bytes/2
        • rsa_private_decrypt/4
        • rsa_private_encrypt/4
        • rsa_public_decrypt/4
        • rsa_public_encrypt/4
        • rsa_sign/4
        • rsa_verify/4
        • crypto_data_decrypt/6
        • crypto_data_encrypt/6
        • crypto_modular_inverse/3
        • crypto_generate_prime/3
        • crypto_is_prime/2
        • crypto_name_curve/2
        • crypto_curve_order/2
        • crypto_curve_generator/2
        • crypto_curve_scalar_mult/4
      • xmlenc.pl -- XML encryption library
      • xmldsig.pl -- XML Digital signature
 crypto_n_random_bytes(+N, -Bytes) is det
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.