View source with formatted comments or as raw
    1/*  Part of SWI-Prolog
    2
    3    Author:        Markus Triska and Matt Lilley
    4    WWW:           http://www.swi-prolog.org
    5    Copyright (c)  2004-2017, SWI-Prolog Foundation
    6                              VU University Amsterdam
    7    All rights reserved.
    8
    9    Redistribution and use in source and binary forms, with or without
   10    modification, are permitted provided that the following conditions
   11    are met:
   12
   13    1. Redistributions of source code must retain the above copyright
   14       notice, this list of conditions and the following disclaimer.
   15
   16    2. Redistributions in binary form must reproduce the above copyright
   17       notice, this list of conditions and the following disclaimer in
   18       the documentation and/or other materials provided with the
   19       distribution.
   20
   21    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   22    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   23    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
   24    FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
   25    COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   26    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
   27    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   28    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   29    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   30    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
   31    ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   32    POSSIBILITY OF SUCH DAMAGE.
   33*/
   34
   35:- module(crypto,
   36          [ crypto_n_random_bytes/2,    % +N, -Bytes
   37            crypto_data_hash/3,         % +Data, -Hash, +Options
   38            crypto_file_hash/3,         % +File, -Hash, +Options
   39            crypto_context_new/2,       % -Context, +Options
   40            crypto_data_context/3,      % +Data, +C0, -C
   41            crypto_context_hash/2,      % +Context, -Hash
   42            crypto_open_hash_stream/3,  % +InStream, -HashStream, +Options
   43            crypto_stream_hash/2,       % +HashStream, -Hash
   44            crypto_password_hash/2,     % +Password, ?Hash
   45            crypto_password_hash/3,     % +Password, ?Hash, +Options
   46            crypto_data_hkdf/4,         % +Data, +Length, -Bytes, +Options
   47            ecdsa_sign/4,               % +Key, +Data, -Signature, +Options
   48            ecdsa_verify/4,             % +Key, +Data, +Signature, +Options
   49            ed25519_new_keypair/1,      % -KeyPair
   50            ed25519_seed_keypair/2,     % +Seed, -KeyPair
   51            ed25519_keypair_public_key/2,   % +KeyPair, -PublicKey
   52            ed25519_sign/4,             % +KeyPair, +Data, -Signature, +Options
   53            ed25519_verify/4,           % +PublicKey, +Data, +Signature, +Options
   54            curve25519_generator/1,     % -Generator
   55            curve25519_scalar_mult/3,   % +Scalar, +Point, -Result
   56            crypto_data_decrypt/6,      % +CipherText, +Algorithm, +Key, +IV, -PlainText, +Options
   57            crypto_data_encrypt/6,      % +PlainText, +Algorithm, +Key, +IV, -CipherText, +Options
   58            hex_bytes/2,                % ?Hex, ?List
   59            rsa_private_decrypt/4,      % +Key, +Ciphertext, -Plaintext, +Enc
   60            rsa_private_encrypt/4,      % +Key, +Plaintext, -Ciphertext, +Enc
   61            rsa_public_decrypt/4,       % +Key, +Ciphertext, -Plaintext, +Enc
   62            rsa_public_encrypt/4,       % +Key, +Plaintext, -Ciphertext, +Enc
   63            rsa_sign/4,                 % +Key, +Data, -Signature, +Options
   64            rsa_verify/4,               % +Key, +Data, +Signature, +Options
   65            crypto_modular_inverse/3,   % +X, +M, -Y
   66            crypto_generate_prime/3,    % +N, -P, +Options
   67            crypto_is_prime/2,          % +P, +Options
   68            crypto_name_curve/2,        % +Name, -Curve
   69            crypto_curve_order/2,       % +Curve, -Order
   70            crypto_curve_generator/2,   % +Curve, -Generator
   71            crypto_curve_scalar_mult/4  % +Curve, +Scalar, +Point, -Result
   72          ]).   73:- autoload(library(apply),[foldl/4,maplist/2,maplist/3]).   74:- autoload(library(base64),[base64_encoded/3]).   75:- autoload(library(error),[must_be/2,domain_error/2]).   76:- autoload(library(lists),[append/2,append/3,select/3,reverse/2]).   77:- autoload(library(option),[option/3,option/2]).   78
   79:- use_foreign_library(foreign(crypto4pl)).   80
   81
   82/** <module> Cryptography and authentication library
   83
   84This library provides bindings  to  functionality   of  OpenSSL  that is
   85related to cryptography and authentication,   not  necessarily involving
   86connections, sockets or streams.
   87
   88The  hash functionality  of this  library subsumes  and extends  that of
   89`library(sha)`, `library(hash_stream)` and `library(md5)` by providing a
   90unified interface to all available digest algorithms.
   91
   92The underlying  OpenSSL library  (`libcrypto`) is dynamically  loaded if
   93_either_ `library(crypto)`  or `library(ssl)` are loaded.  Therefore, if
   94your application uses `library(ssl)`,  you can use `library(crypto)` for
   95hashing without increasing the memory  footprint of your application. In
   96other cases, the specialised hashing  libraries are more lightweight but
   97less general alternatives to `library(crypto)`.
   98
   99@author [Markus Triska](https://www.metalevel.at)
  100@author Matt Lilley
  101*/
  102
  103%%  crypto_n_random_bytes(+N, -Bytes) is det
  104%
  105%   Bytes is unified with a list of N cryptographically secure
  106%   pseudo-random bytes. Each byte is an integer between 0 and 255. If
  107%   the internal pseudo-random number generator (PRNG) has not been
  108%   seeded with enough entropy to ensure an unpredictable byte
  109%   sequence, an exception is thrown.
  110%
  111%   One way to relate such a list of bytes to an _integer_ is to use
  112%   CLP(FD) constraints as follows:
  113%
  114%   ==
  115%   :- use_module(library(clpfd)).
  116%
  117%   bytes_integer(Bs, N) :-
  118%           foldl(pow, Bs, 0-0, N-_).
  119%
  120%   pow(B, N0-I0, N-I) :-
  121%           B in 0..255,
  122%           N #= N0 + B*256^I0,
  123%           I #= I0 + 1.
  124%   ==
  125%
  126%   With this definition, you can generate a random 256-bit integer
  127%   _from_ a list of 32 random _bytes_:
  128%
  129%   ==
  130%   ?- crypto_n_random_bytes(32, Bs),
  131%      bytes_integer(Bs, I).
  132%   Bs = [98, 9, 35, 100, 126, 174, 48, 176, 246|...],
  133%   I = 109798276762338328820827...(53 digits omitted).
  134%   ==
  135%
  136%   The above relation also works in the other direction, letting you
  137%   translate an integer _to_ a list of bytes. In addition, you can
  138%   use hex_bytes/2 to convert bytes to _tokens_ that can be easily
  139%   exchanged in your applications. This also works if you have
  140%   compiled SWI-Prolog without support for large integers.
  141
  142
  143/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  144   SHA256 is the current default for several hash-related predicates.
  145   It is deemed sufficiently secure for the foreseeable future.  Yet,
  146   application programmers must be aware that the default may change in
  147   future versions. The hash predicates all yield the algorithm they
  148   used if a Prolog variable is used for the pertaining option.
  149- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
  150
  151default_hash(sha256).
  152
  153functor_hash_options(F, Hash, Options0, [Option|Options]) :-
  154        Option =.. [F,Hash],
  155        (   select(Option, Options0, Options) ->
  156            (   var(Hash) ->
  157                default_hash(Hash)
  158            ;   must_be(atom, Hash)
  159            )
  160        ;   Options = Options0,
  161            default_hash(Hash)
  162        ).
  163
  164
  165%%  crypto_data_hash(+Data, -Hash, +Options) is det
  166%
  167%   Hash is the hash of Data. The conversion is controlled
  168%   by Options:
  169%
  170%    * algorithm(+Algorithm)
  171%    One of =md5= (_insecure_), =sha1= (_insecure_), =ripemd160=,
  172%    =sha224=, =sha256=, =sha384=, =sha512=, =sha3_224=, =sha3_256=,
  173%    =sha3_384=, =sha3_512=, =blake2s256= or =blake2b512=. The BLAKE
  174%    digest algorithms require OpenSSL 1.1.0 or greater, and the SHA-3
  175%    algorithms require OpenSSL 1.1.1 or greater. The default is a
  176%    cryptographically secure algorithm. If you specify a variable,
  177%    then that variable is unified with the algorithm that was used.
  178%    * encoding(+Encoding)
  179%    If Data is a sequence of character _codes_, this must be
  180%    translated into a sequence of _bytes_, because that is what
  181%    the hashing requires.  The default encoding is =utf8=.  The
  182%    other meaningful value is =octet=, claiming that Data contains
  183%    raw bytes.
  184%    * hmac(+Key)
  185%    If this option is specified, a _hash-based message authentication
  186%    code_ (HMAC) is computed, using the specified Key which is either
  187%    an atom, string or list of _bytes_. Any of the available digest
  188%    algorithms can be used with this option. The cryptographic
  189%    strength of the HMAC depends on that of the chosen algorithm and
  190%    also on the key. This option requires OpenSSL 1.1.0 or greater.
  191%
  192%  @param Data is either an atom, string or code-list
  193%  @param Hash is an atom that represents the hash in hexadecimal encoding.
  194%
  195%  @see hex_bytes/2 for conversion between hexadecimal encoding and
  196%  lists of bytes.
  197%  @see crypto_password_hash/2 for the important use case of passwords.
  198
  199crypto_data_hash(Data, Hash, Options) :-
  200    crypto_context_new(Context0, Options),
  201    crypto_data_context(Data, Context0, Context),
  202    crypto_context_hash(Context, Hash).
  203
  204%!  crypto_file_hash(+File, -Hash, +Options) is det.
  205%
  206%   True if  Hash is the hash  of the content of  File. For Options,
  207%   see crypto_data_hash/3.
  208
  209crypto_file_hash(File, Hash, Options) :-
  210    setup_call_cleanup(open(File, read, In, [type(binary)]),
  211                       crypto_stream_hash(In, Hash, Options),
  212                       close(In)).
  213
  214crypto_stream_hash(Stream, Hash, Options) :-
  215    crypto_context_new(Context0, Options),
  216    update_hash(Stream, Context0, Context),
  217    crypto_context_hash(Context, Hash).
  218
  219update_hash(In, Context0, Context) :-
  220    (   at_end_of_stream(In)
  221    ->  Context = Context0
  222    ;   read_pending_codes(In, Data, []),
  223        crypto_data_context(Data, Context0, Context1),
  224        update_hash(In, Context1, Context)
  225    ).
  226
  227
  228%!  crypto_context_new(-Context, +Options) is det.
  229%
  230%   Context is  unified with  the empty  context, taking  into account
  231%   Options.  The  context can be used  in crypto_data_context/3.  For
  232%   Options, see crypto_data_hash/3.
  233%
  234%   @param Context is an opaque pure  Prolog term that is subject to
  235%          garbage collection.
  236
  237crypto_context_new(Context, Options0) :-
  238    functor_hash_options(algorithm, _, Options0, Options),
  239    '_crypto_context_new'(Context, Options).
  240
  241
  242%!  crypto_data_context(+Data, +Context0, -Context) is det
  243%
  244%   Context0 is an existing computation  context, and Context is the
  245%   new context  after hashing  Data in  addition to  the previously
  246%   hashed data.  Context0 may be  produced by a prior invocation of
  247%   either crypto_context_new/2 or crypto_data_context/3 itself.
  248%
  249%   This predicate allows a hash to be computed in chunks, which may
  250%   be important while working  with Metalink (RFC 5854), BitTorrent
  251%   or similar technologies, or simply with big files.
  252
  253crypto_data_context(Data, Context0, Context) :-
  254    '_crypto_hash_context_copy'(Context0, Context),
  255    '_crypto_update_hash_context'(Data, Context).
  256
  257
  258%!  crypto_context_hash(+Context, -Hash)
  259%
  260%   Obtain the  hash code of  Context. Hash is an  atom representing
  261%   the hash code  that is associated with the current  state of the
  262%   computation context Context.
  263
  264crypto_context_hash(Context, Hash) :-
  265    '_crypto_hash_context_copy'(Context, Copy),
  266    '_crypto_hash_context_hash'(Copy, List),
  267    hex_bytes(Hash, List).
  268
  269%!  crypto_open_hash_stream(+OrgStream, -HashStream, +Options) is det.
  270%
  271%   Open a filter stream on OrgStream  that maintains a hash. The hash
  272%   can be retrieved at any time using crypto_stream_hash/2. Available
  273%   Options in addition to those of crypto_data_hash/3 are:
  274%
  275%     - close_parent(+Bool)
  276%     If `true` (default), closing the filter stream also closes the
  277%     original (parent) stream.
  278
  279crypto_open_hash_stream(OrgStream, HashStream, Options) :-
  280    crypto_context_new(Context, Options),
  281    '_crypto_open_hash_stream'(OrgStream, HashStream, Context).
  282
  283
  284%!  crypto_stream_hash(+HashStream, -Hash) is det.
  285%
  286%   Unify  Hash with  a hash  for  the bytes  sent to  or read  from
  287%   HashStream.  Note  that  the  hash is  computed  on  the  stream
  288%   buffers. If the stream is an  output stream, it is first flushed
  289%   and the Digest  represents the hash at the  current location. If
  290%   the stream is an input stream  the Digest represents the hash of
  291%   the processed input including the already buffered data.
  292
  293crypto_stream_hash(Stream, Hash) :-
  294    '_crypto_stream_hash_context'(Stream, Context),
  295    crypto_context_hash(Context, Hash).
  296
  297/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  298   The so-called modular crypt format (MCF) is a standard for encoding
  299   password hash strings. However, there's no official specification
  300   document describing it. Nor is there a central registry of
  301   identifiers or rules. This page describes what is known about it:
  302
  303   https://pythonhosted.org/passlib/modular_crypt_format.html
  304
  305   As of 2016, the MCF is deprecated in favor of the PHC String Format:
  306
  307   https://github.com/P-H-C/phc-string-format/blob/master/phc-sf-spec.md
  308
  309   This is what we are using below. For the time being, it is best to
  310   treat these hashes as opaque atoms in applications. Please let me
  311   know if you need to rely on any specifics of this format.
  312- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
  313
  314%!  crypto_password_hash(+Password, ?Hash) is semidet.
  315%
  316%   If  Hash is  instantiated,  the predicate  succeeds  _iff_ the  hash
  317%   matches the  given password.  Otherwise, the  call is  equivalent to
  318%   crypto_password_hash(Password,    Hash,   [])    and   computes    a
  319%   password-based hash using the default options.
  320
  321crypto_password_hash(Password, Hash) :-
  322    (   nonvar(Hash) ->
  323        must_be(atom, Hash),
  324        split_string(Hash, "$", "$", Parts),
  325        ( Parts = ["pbkdf2-sha512",Ps,SaltB64,HashB64] ->
  326          atom_to_term(Ps, t=Iterations, []),
  327          bytes_base64(SaltBytes, SaltB64),
  328          bytes_base64(HashBytes, HashB64),
  329          '_crypto_password_hash_pbkdf2'(Password, SaltBytes, Iterations, HashBytes)
  330        ; Parts = ["2a", _, _],
  331          sub_atom(Hash, 0, 29, 31, Setting),
  332          '_crypto_password_hash_bcrypt'(Password, Setting, Hash)
  333        )
  334    ;   crypto_password_hash(Password, Hash, [])
  335    ).
  336
  337%!  crypto_password_hash(+Password, -Hash, +Options) is det.
  338%
  339%   Derive  Hash  based  on  Password.  This  predicate  is  similar  to
  340%   crypto_data_hash/3  in  that it  derives  a  hash from  given  data.
  341%   However,   it   is  tailored   for   the   specific  use   case   of
  342%   _passwords_. One  essential distinction is  that for this  use case,
  343%   the  derivation  of a  hash  should  be  _as  slow as  possible_  to
  344%   counteract brute-force attacks over possible passwords.
  345%
  346%   Another important  distinction is  that equal passwords  must yield,
  347%   with  very high  probability, _different_  hashes. For  this reason,
  348%   cryptographically strong  random numbers are automatically  added to
  349%   the password before a hash is derived.
  350%
  351%   Hash is unified with an atom that contains the computed hash and all
  352%   parameters  that were  used, except  for the  password.  Instead  of
  353%   storing passwords,  store these  hashes. Later,  you can  verify the
  354%   validity of  a password  with crypto_password_hash/2,  comparing the
  355%   then entered password to the stored hash. If you need to export this
  356%   atom, you should treat it as opaque  ASCII data with up to 255 bytes
  357%   of length. The maximal length may increase in the future.
  358%
  359%   Admissible options are:
  360%
  361%     - algorithm(+Algorithm)
  362%       The algorithm to use. Currently, the only available algorithms
  363%       are =|pbkdf2-sha512|= (the default) and =bcrypt=.
  364%     - cost(+C)
  365%       C is an integer, denoting the binary logarithm of the number
  366%       of _iterations_ used for the derivation of the hash. This
  367%       means that the number of iterations is set to 2^C. Currently,
  368%       the default is 17, and thus more than one hundred _thousand_
  369%       iterations. You should set this option as high as your server
  370%       and users can tolerate. The default is subject to change and
  371%       will likely increase in the future or adapt to new algorithms.
  372%     - salt(+Salt)
  373%       Use the given list of bytes as salt. By default,
  374%       cryptographically secure random numbers are generated for this
  375%       purpose. The default is intended to be secure, and constitutes
  376%       the typical use case of this predicate.
  377%
  378%   Currently,  PBKDF2  with SHA-512  is  used  as the  hash  derivation
  379%   function, using 128 bits of  salt. All default parameters, including
  380%   the algorithm, are subject to change, and other algorithms will also
  381%   become available  in the  future.  Since  computed hashes  store all
  382%   parameters that were used during their derivation, such changes will
  383%   not affect the  operation of existing deployments.  Note though that
  384%   new hashes will then be computed with the new default parameters.
  385%
  386%   @see crypto_data_hkdf/4 for generating keys from Hash.
  387
  388crypto_password_hash(Password, Hash, Options) :-
  389    must_be(list, Options),
  390    option(cost(C), Options, 17),
  391    Iterations is 2^C,
  392    option(algorithm(Algorithm), Options, 'pbkdf2-sha512'),
  393    memberchk(Algorithm, ['pbkdf2-sha512', bcrypt]),
  394    (   option(salt(SaltBytes), Options) ->
  395        true
  396    ;   crypto_n_random_bytes(16, SaltBytes)
  397    ),
  398    (  Algorithm == 'pbkdf2-sha512'
  399    -> '_crypto_password_hash_pbkdf2'(Password, SaltBytes, Iterations, HashBytes),
  400       bytes_base64(HashBytes, HashB64),
  401       bytes_base64(SaltBytes, SaltB64),
  402       format(atom(Hash),
  403              "$pbkdf2-sha512$t=~d$~w$~w", [Iterations,SaltB64,HashB64])
  404    ;  bcrypt_bytes_base64(SaltBytes, SaltB64),
  405       option(cost(Cost), Options, 11),
  406       format(string(Setting), "$2a$~|~`0t~d~2+$~w", [Cost, SaltB64]),
  407       '_crypto_password_hash_bcrypt'(Password, Setting, Hash)
  408    ).
  409
  410
  411/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  412   Bidirectional Bytes <-> Base64 conversion as required by PHC format.
  413
  414   Note that *no padding* must be used, and that we must be able
  415   to encode the whole range of bytes, not only UTF-8 sequences!
  416- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
  417
  418bytes_base64(Bytes, Base64) :-
  419    (   var(Bytes) ->
  420        base64_encoded(Atom, Base64, [padding(false), encoding(iso_latin_1)]),
  421        atom_codes(Atom, Bytes)
  422    ;   atom_codes(Atom, Bytes),
  423        base64_encoded(Atom, Base64, [padding(false), encoding(iso_latin_1)])
  424    ).
  425
  426% Bcrypt uses a different alphabeta for base64 encoding, annoyingly
  427bcrypt_bytes_base64(Bytes, Base64) :-
  428    (   var(Bytes) ->
  429        base64_encoded(Atom, Base64, [padding(false), encoding(utf8),
  430                                      charset(openbsd)]),
  431        atom_codes(Atom, Bytes)
  432    ;   atom_codes(Atom, Bytes),
  433        base64_encoded(Atom, Base64, [padding(false), encoding(utf8),
  434                                      charset(openbsd)])
  435    ).
  436
  437
  438%!  crypto_data_hkdf(+Data, +Length, -Bytes, +Options) is det.
  439%
  440%   Concentrate possibly dispersed entropy of Data and then expand it to
  441%   the desired  length.  Bytes  is unified  with a  list of  _bytes_ of
  442%   length  Length,  and  is  suitable  as  input  keying  material  and
  443%   initialization vectors to the symmetric encryption predicates.
  444%
  445%   Admissible options are:
  446%
  447%      - algorithm(+Algorithm)
  448%        A hashing algorithm as specified to crypto_data_hash/3. The
  449%        default is a cryptographically secure algorithm. If you
  450%        specify a variable, then it is unified with the algorithm
  451%        that was used.
  452%      - info(+Info)
  453%        Optional context and application specific information,
  454%        specified as an atom, string or list of _bytes_. The default
  455%        is the zero length atom ''.
  456%      - salt(+List)
  457%        Optionally, a list of _bytes_ that are used as salt. The
  458%        default is all zeroes.
  459%      - encoding(+Atom)
  460%        Either =|utf8|= (default) or =|octet|=, denoting
  461%        the representation of Data as in crypto_data_hash/3.
  462%
  463%   The `info/1`  option can be  used to  generate multiple keys  from a
  464%   single  master key,  using for  example values  such as  =|key|= and
  465%   =|iv|=, or the name of a file that is to be encrypted.
  466%
  467%   This predicate requires OpenSSL 1.1.0 or greater.
  468%
  469%   @see crypto_n_random_bytes/2 to obtain a suitable salt.
  470%   @see crypto_data_hash/3 to compute a HMAC signature.
  471
  472
  473crypto_data_hkdf(Data, L, Bytes, Options0) :-
  474        functor_hash_options(algorithm, Algorithm, Options0, Options),
  475        option(salt(SaltBytes), Options, []),
  476        option(info(Info), Options, ''),
  477        option(encoding(Enc), Options, utf8),
  478        '_crypto_data_hkdf'(Data, SaltBytes, Info, Algorithm, Enc, L, Bytes).
  479
  480%!  ecdsa_sign(+Key, +Data, -Signature, +Options)
  481%
  482%   Create  an ECDSA  signature for  Data with  EC private  key Key.
  483%   Among the most  common cases is signing a hash  that was created
  484%   with crypto_data_hash/3 or other predicates of this library. For
  485%   this reason, the  default encoding (`hex`) assumes  that Data is
  486%   an atom,  string, character list  or code list  representing the
  487%   data in hexadecimal notation. See rsa_sign/4 for an example.
  488%
  489%   Options:
  490%
  491%     - encoding(+Encoding)
  492%     Encoding to use for Data.  Default is `hex`.  Alternatives
  493%     are `octet`, `utf8` and `text`.
  494
  495ecdsa_sign(private_key(ec(Private,Public0,Curve)), Data0, Signature, Options) :-
  496    option(encoding(Enc0), Options, hex),
  497    hex_encoding(Enc0, Data0, Enc, Data),
  498    hex_bytes(Public0, Public),
  499    '_crypto_ecdsa_sign'(ec(Private,Public,Curve), Data, Enc, Signature).
  500
  501hex_encoding(hex, Data0, octet, Data) :- !,
  502    hex_bytes(Data0, Data).
  503hex_encoding(Enc, Data, Enc, Data).
  504
  505%!  ecdsa_verify(+Key, +Data, +Signature, +Options) is semidet.
  506%
  507%   True iff Signature can be verified as the ECDSA signature for
  508%   Data, using the EC public key Key.
  509%
  510%   Options:
  511%
  512%     - encoding(+Encoding)
  513%     Encoding to use for Data.  Default is `hex`.  Alternatives
  514%     are `octet`, `utf8` and `text`.
  515
  516ecdsa_verify(public_key(ec(Private,Public0,Curve)), Data0, Signature0, Options) :-
  517    option(encoding(Enc0), Options, hex),
  518    hex_encoding(Enc0, Data0, Enc, Data),
  519    hex_bytes(Public0, Public),
  520    hex_bytes(Signature0, Signature),
  521    '_crypto_ecdsa_verify'(ec(Private,Public,Curve), Data, Enc, Signature).
  522
  523
  524                 /*******************************
  525                 *            ED25519           *
  526                 *******************************/
  527
  528%!  ed25519_new_keypair(-KeyPair) is det.
  529%
  530%   KeyPair is a new Ed25519 key  pair,   created  from  32 random bytes
  531%   obtained with crypto_n_random_bytes/2. It contains the private key
  532%   and must be kept absolutely secret. See ed25519_seed_keypair/2.
  533
  534ed25519_new_keypair(KeyPair) :-
  535    crypto_n_random_bytes(32, Seed),
  536    ed25519_seed_keypair(Seed, KeyPair).
  537
  538%!  ed25519_seed_keypair(+Seed, -KeyPair) is det.
  539%
  540%   Deterministically  derive  an  Ed25519  key   pair  from  Seed,  32
  541%   arbitrary bytes.  Seed can be  chosen  at random using
  542%   crypto_n_random_bytes/2  or  derived  from  input  keying  material
  543%   using crypto_data_hkdf/4.
  544%
  545%   KeyPair  is  a  hexadecimal  atom  denoting  the  key  pair  in
  546%   PKCS#8 v2 format (RFC 5958, RFC 8410), the format also used by
  547%   ``openssl genpkey -algorithm ed25519``.  It contains the private key
  548%   and must be kept absolutely secret.  It can be used for signing
  549%   with ed25519_sign/4, and its public key is obtained with
  550%   ed25519_keypair_public_key/2.
  551
  552ed25519_seed_keypair(Seed0, KeyPair) :-
  553    key_bytes(Seed0, 32, Seed),
  554    '_crypto_ed25519_seed_public_key'(Seed, PublicKey),
  555    append([[0x30,81,           % SEQUENCE of 81 bytes
  556             2,1,1,             % INTEGER 1: version v2, public key included
  557             0x30,5,            % privateKeyAlgorithm: SEQUENCE of 5 bytes
  558             6,3,43,101,112,    % OBJECT IDENTIFIER 1.3.101.112 (Ed25519)
  559             4,34,4,32],        % privateKey: OCTET STRING of an OCTET STRING
  560            Seed,
  561            [0x81,33,0],        % publicKey: [1] IMPLICIT BIT STRING, 0 unused
  562            PublicKey], Bytes),
  563    hex_bytes(KeyPair, Bytes).
  564
  565%!  ed25519_keypair_public_key(+KeyPair, -PublicKey) is det.
  566%
  567%   PublicKey is  the public key  of KeyPair, a hexadecimal  atom.  The
  568%   public key is used for signature verification with ed25519_verify/4
  569%   and can be shared freely.
  570
  571ed25519_keypair_public_key(KeyPair, PublicKey) :-
  572    keypair_bytes(KeyPair, Bytes),
  573    length(Prefix, 51),
  574    append(Prefix, Public, Bytes),
  575    hex_bytes(PublicKey, Public).
  576
  577%!  ed25519_sign(+KeyPair, +Data, -Signature, +Options) is det.
  578%
  579%   Create an Ed25519 (RFC 8032) signature for Data with the private
  580%   key of KeyPair, as created by ed25519_new_keypair/1 or obtained
  581%   with load_private_key/3.  Signature is a hexadecimal atom.
  582%
  583%   Options:
  584%
  585%     - encoding(+Encoding)
  586%     Encoding to use for Data.  Default is `utf8`.  Alternatives are
  587%     `octet`, `text` and `hex`.  Note that this differs from
  588%     ecdsa_sign/4 and rsa_sign/4, which default to `hex` because they
  589%     are typically applied to a _hash_ of the data.  Ed25519 signs the
  590%     data itself.
  591
  592ed25519_sign(KeyPair, Data0, Signature, Options) :-
  593    keypair_private_key(KeyPair, Seed),
  594    option(encoding(Enc0), Options, utf8),
  595    hex_encoding(Enc0, Data0, Enc, Data),
  596    '_crypto_ed25519_sign'(Seed, Data, Enc, Bytes),
  597    hex_bytes(Signature, Bytes).
  598
  599%!  ed25519_verify(+PublicKey, +Data, +Signature, +Options) is semidet.
  600%
  601%   True iff Signature can be verified as the Ed25519 signature for
  602%   Data, using PublicKey.
  603%
  604%   Options are as for ed25519_sign/4.
  605
  606ed25519_verify(Key, Data0, Signature0, Options) :-
  607    public_key_bytes(Key, PublicKey),
  608    option(encoding(Enc0), Options, utf8),
  609    hex_encoding(Enc0, Data0, Enc, Data),
  610    key_bytes(Signature0, 64, Signature),
  611    '_crypto_ed25519_verify'(PublicKey, Data, Enc, Signature).
  612
  613keypair_private_key(KeyPair, Seed) :-
  614    keypair_bytes(KeyPair, Bytes),
  615    length(Prefix, 16),
  616    append(Prefix, Rest, Bytes),
  617    length(Seed, 32),
  618    append(Seed, _, Rest).
  619
  620keypair_bytes(private_key(ed25519(KeyPair)), Bytes) :-
  621    !,
  622    key_bytes(KeyPair, 83, Bytes).
  623keypair_bytes(KeyPair, Bytes) :-
  624    key_bytes(KeyPair, 83, Bytes).
  625
  626public_key_bytes(public_key(ed25519(Key)), Bytes) :-
  627    !,
  628    key_bytes(Key, 32, Bytes).
  629public_key_bytes(Key, Bytes) :-
  630    key_bytes(Key, 32, Bytes).
  631
  632%!  key_bytes(+Spec, +Length, -Bytes) is det.
  633%
  634%   Bytes is the list of Length bytes denoted by Spec.  A list of
  635%   integers is a list of bytes, as produced by crypto_n_random_bytes/2.
  636%   Anything else is a hexadecimal atom, string or list of characters,
  637%   as produced by hex_bytes/2.
  638
  639key_bytes(Spec, Length, Bytes) :-
  640    (   is_list(Spec),
  641        maplist(integer, Spec)
  642    ->  must_be(list(between(0,255)), Spec),
  643        Bytes = Spec
  644    ;   hex_bytes(Spec, Bytes)
  645    ),
  646    (   length(Bytes, Length)
  647    ->  true
  648    ;   domain_error(bytes(Length), Spec)
  649    ).
  650
  651
  652                 /*******************************
  653                 *            X25519            *
  654                 *******************************/
  655
  656%!  curve25519_generator(-Generator) is det.
  657%
  658%   Points on  Curve25519 are  hexadecimal atoms  denoting the
  659%   u-coordinate  of  the  Montgomery  curve.   Generator  is  the
  660%   generator point of Curve25519.
  661
  662curve25519_generator(Generator) :-
  663    length(Zeroes, 31),
  664    maplist(=(0), Zeroes),
  665    hex_bytes(Generator, [9|Zeroes]).
  666
  667%!  curve25519_scalar_mult(+Scalar, +Point, -Result) is semidet.
  668%
  669%   Result is the point _Scalar*Point_ on Curve25519, as mandated by
  670%   X25519 (RFC 7748).  Scalar is an integer between 0 and 2^256-1, or
  671%   32 bytes.  Fails if Point has small order, i.e., if the result
  672%   would be the point at infinity.
  673%
  674%   Alice and Bob can use  this   to  establish a shared secret, where
  675%   Generator is obtained with curve25519_generator/1:
  676%
  677%     1. Alice creates a random integer _a_ and sends _As = a*Generator_
  678%        to Bob.
  679%     2. Bob creates a random integer _b_ and sends _Bs = b*Generator_
  680%        to Alice.
  681%     3. Alice computes _Rs = a*Bs_.
  682%     4. Bob computes _Rs = b*As_.
  683%     5. Alice and Bob use crypto_data_hkdf/4 on Rs with suitable (same)
  684%        parameters to obtain keys and initialization vectors for
  685%        symmetric encryption.
  686%
  687%   If _a_ and _b_ are kept secret, this method is considered very
  688%   secure.
  689
  690curve25519_scalar_mult(Scalar0, Point0, Result) :-
  691    (   integer(Scalar0)
  692    ->  integer_key_bytes(Scalar0, 32, Scalar)
  693    ;   key_bytes(Scalar0, 32, Scalar)
  694    ),
  695    key_bytes(Point0, 32, Point),
  696    '_crypto_curve25519_scalar_mult'(Scalar, Point, Bytes),
  697    hex_bytes(Result, Bytes).
  698
  699%!  integer_key_bytes(+Integer, +Length, -Bytes) is det.
  700%
  701%   Bytes is the little-endian representation of Integer using Length
  702%   bytes, the byte order mandated by X25519.
  703
  704integer_key_bytes(Integer, Length, Bytes) :-
  705    must_be(nonneg, Integer),
  706    (   Integer >> (8*Length) =:= 0
  707    ->  true
  708    ;   domain_error(bytes(Length), Integer)
  709    ),
  710    integer_bytes(Length, Integer, Bytes).
  711
  712integer_bytes(0, _, []) :-
  713    !.
  714integer_bytes(Length0, Integer, [Byte|Bytes]) :-
  715    Byte is Integer /\ 0xff,
  716    Integer1 is Integer>>8,
  717    Length is Length0-1,
  718    integer_bytes(Length, Integer1, Bytes).
  719
  720
  721%!  hex_bytes(?Hex, ?List) is det.
  722%
  723%   Relation between a hexadecimal sequence  and a list of bytes.  Hex
  724%   is  an atom,  string,  list  of characters  or  list  of codes  in
  725%   hexadecimal  encoding.   This  is  the  format  that  is  used  by
  726%   crypto_data_hash/3 and  related predicates to  represent _hashes_.
  727%   Bytes is a list of _integers_ between 0 and 255 that represent the
  728%   sequence as a  list of bytes.  At least one  of the arguments must
  729%   be instantiated. When converting List  _to_ Hex, an _atom_ is used
  730%   to represent the sequence of hexadecimal digits.
  731%
  732%   Example:
  733%
  734%   ==
  735%   ?- hex_bytes('501ACE', Bs).
  736%   Bs = [80, 26, 206].
  737%   ==
  738%
  739%  @see base64_encoded/3 for Base64 encoding, which is often used to
  740%  transfer or embed binary data in applications.
  741
  742hex_bytes(Hs, Bytes) :-
  743    (   ground(Hs) ->
  744        string_chars(Hs, Chars),
  745        (   phrase(hex_bytes(Chars), Bytes)
  746        ->  true
  747        ;   domain_error(hex_encoding, Hs)
  748        )
  749    ;   must_be(list(between(0,255)), Bytes),
  750        phrase(bytes_hex(Bytes), Chars),
  751        atom_chars(Hs, Chars)
  752    ).
  753
  754hex_bytes([]) --> [].
  755hex_bytes([H1,H2|Hs]) --> [Byte],
  756    { char_type(H1, xdigit(High)),
  757      char_type(H2, xdigit(Low)),
  758      Byte is High*16 + Low },
  759    hex_bytes(Hs).
  760
  761bytes_hex([]) --> [].
  762bytes_hex([B|Bs]) -->
  763    { High is B>>4,
  764      Low is B /\ 0xf,
  765      char_type(C0, xdigit(High)),
  766      char_type(C1, xdigit(Low))
  767    },
  768    [C0,C1],
  769    bytes_hex(Bs).
  770
  771%!  rsa_private_decrypt(+PrivateKey, +CipherText, -PlainText, +Options) is det.
  772%!  rsa_private_encrypt(+PrivateKey, +PlainText, -CipherText, +Options) is det.
  773%!  rsa_public_decrypt(+PublicKey, +CipherText, -PlainText, +Options) is det.
  774%!  rsa_public_encrypt(+PublicKey, +PlainText, -CipherText, +Options) is det.
  775%
  776%   RSA Public key encryption and   decryption  primitives. A string
  777%   can be safely communicated by first   encrypting it and have the
  778%   peer decrypt it with the matching  key and predicate. The length
  779%   of the string is limited by  the   key  length.
  780%
  781%   Options:
  782%
  783%     - encoding(+Encoding)
  784%     Encoding to use for Data.  Default is `utf8`.  Alternatives
  785%     are `utf8` and `octet`.
  786%
  787%     - padding(+PaddingScheme)
  788%     Padding scheme to use.  Default is `pkcs1`.  Alternatives
  789%     are `pkcs1_oaep`, `sslv23` and `none`. Note that `none` should
  790%     only be used if you implement cryptographically sound padding
  791%     modes in your application code as encrypting unpadded data with
  792%     RSA is insecure
  793%
  794%   @see load_private_key/3, load_public_key/2 can be use to load
  795%   keys from a file.  The predicate load_certificate/2 can be used
  796%   to obtain the public key from a certificate.
  797%
  798%   @error ssl_error(Code, LibName, FuncName, Reason)   is raised if
  799%   there is an error, e.g., if the text is too long for the key.
  800
  801%!  rsa_sign(+Key, +Data, -Signature, +Options) is det.
  802%
  803%   Create an RSA signature for Data with private key Key.  Options:
  804%
  805%     - type(+Type)
  806%     SHA algorithm used to compute the digest.  Values are
  807%     `sha1`, `sha224`, `sha256`, `sha384` or `sha512`. The
  808%     default is a cryptographically secure algorithm. If you
  809%     specify a variable, then it is unified with the algorithm that
  810%     was used.
  811%
  812%     - encoding(+Encoding)
  813%     Encoding to use for Data.  Default is `hex`.  Alternatives
  814%     are `octet`, `utf8` and `text`.
  815%
  816%   This predicate can be used to compute a =|sha256WithRSAEncryption|=
  817%   signature as follows:
  818%
  819%     ```
  820%     sha256_with_rsa(PemKeyFile, Password, Data, Signature) :-
  821%         Algorithm = sha256,
  822%         read_key(PemKeyFile, Password, Key),
  823%         crypto_data_hash(Data, Hash, [algorithm(Algorithm),
  824%                                       encoding(octet)]),
  825%         rsa_sign(Key, Hash, Signature, [type(Algorithm)]).
  826%
  827%     read_key(File, Password, Key) :-
  828%         setup_call_cleanup(
  829%             open(File, read, In, [type(binary)]),
  830%             load_private_key(In, Password, Key),
  831%             close(In)).
  832%     ```
  833%
  834%   Note that a hash that is computed by crypto_data_hash/3 can be
  835%   directly used in rsa_sign/4 as well as ecdsa_sign/4.
  836
  837rsa_sign(Key, Data0, Signature, Options0) :-
  838    functor_hash_options(type, Type, Options0, Options),
  839    option(encoding(Enc0), Options, hex),
  840    hex_encoding(Enc0, Data0, Enc, Data),
  841    rsa_sign(Key, Type, Enc, Data, Signature).
  842
  843
  844%!  rsa_verify(+Key, +Data, +Signature, +Options) is semidet.
  845%
  846%   Verify an RSA signature for Data with public key Key.
  847%
  848%   Options:
  849%
  850%     - type(+Type)
  851%     SHA algorithm used to compute the digest.  Values are `sha1`,
  852%     `sha224`, `sha256`, `sha384` or `sha512`. The default is the
  853%     same as for rsa_sign/4.  This option must match the algorithm
  854%     that was used for signing. When operating with different parties,
  855%     the used algorithm must be communicated over an authenticated
  856%     channel.
  857%
  858%     - encoding(+Encoding)
  859%     Encoding to use for Data.  Default is `hex`.  Alternatives
  860%     are `octet`, `utf8` and `text`.
  861
  862rsa_verify(Key, Data0, Signature0, Options0) :-
  863    functor_hash_options(type, Type, Options0, Options),
  864    option(encoding(Enc0), Options, hex),
  865    hex_encoding(Enc0, Data0, Enc, Data),
  866    hex_bytes(Signature0, Signature),
  867    rsa_verify(Key, Type, Enc, Data, Signature).
  868
  869%!  crypto_data_decrypt(+CipherText,
  870%!                      +Algorithm,
  871%!                      +Key,
  872%!                      +IV,
  873%!                      -PlainText,
  874%!                      +Options).
  875%
  876%   Decrypt  the   given  CipherText,  using  the   symmetric  algorithm
  877%   Algorithm, key Key, and initialization vector IV, to give PlainText.
  878%   CipherText must  be a string, atom  or list of codes  or characters,
  879%   and PlainText  is created  as a  string.  Key  and IV  are typically
  880%   lists  of _bytes_,  though  atoms and  strings  are also  permitted.
  881%   Algorithm must be an algorithm which your copy of OpenSSL knows. See
  882%   crypto_data_encrypt/6 for an example.
  883%
  884%     - encoding(+Encoding)
  885%     Encoding to use for CipherText.  Default is `utf8`.
  886%     Alternatives are `utf8` and `octet`.
  887%
  888%     - padding(+PaddingScheme)
  889%     For block ciphers, the padding scheme to use.  Default is
  890%     `block`.  You can disable padding by supplying `none` here.
  891%
  892%     - tag(+Tag)
  893%     For authenticated encryption schemes, the tag must be specified as
  894%     a list of bytes exactly as they were generated upon encryption.
  895%     This option requires OpenSSL 1.1.0 or greater.
  896%
  897%     - min_tag_length(+Length)
  898%     If the tag length is smaller than 16, this option must be used
  899%     to permit such shorter tags. This is used as a safeguard against
  900%     truncation attacks, where an attacker provides a short tag that
  901%     is easier to guess.
  902
  903crypto_data_decrypt(CipherText, Algorithm, Key, IV, PlainText, Options) :-
  904        (   option(tag(Tag), Options) ->
  905            option(min_tag_length(MinTagLength), Options, 16),
  906            length(Tag, TagLength),
  907            compare(C, TagLength, MinTagLength),
  908            tag_length_ok(C, Tag)
  909        ;   Tag = []
  910        ),
  911        '_crypto_data_decrypt'(CipherText, Algorithm, Key, IV,
  912                               Tag, PlainText, Options).
  913
  914% This test is important to prevent truncation attacks of the tag.
  915
  916tag_length_ok(=, _).
  917tag_length_ok(>, _).
  918tag_length_ok(<, Tag) :- domain_error(tag_is_too_short, Tag).
  919
  920
  921%!  crypto_data_encrypt(+PlainText,
  922%!                      +Algorithm,
  923%!                      +Key,
  924%!                      +IV,
  925%!                      -CipherText,
  926%!                      +Options).
  927%
  928%   Encrypt  the   given  PlainText,   using  the   symmetric  algorithm
  929%   Algorithm, key Key, and initialization vector (or nonce) IV, to give
  930%   CipherText.
  931%
  932%   PlainText must be a string, atom or list of codes or characters, and
  933%   CipherText is created  as a string.  Key and IV  are typically lists
  934%   of _bytes_, though atoms and  strings are also permitted.  Algorithm
  935%   must   be  an   algorithm   which  your   copy   of  OpenSSL   knows
  936%   about.
  937%
  938%   Keys  and   IVs  can  be   chosen  at  random  (using   for  example
  939%   crypto_n_random_bytes/2) or derived from input keying material (IKM)
  940%   using for example crypto_data_hkdf/4.  This  input is often a shared
  941%   secret, such as a negotiated point on an elliptic curve, or the hash
  942%   that was computed from a  password via crypto_password_hash/3 with a
  943%   freshly generated and specified _salt_.
  944%
  945%   Reusing the same combination of Key  and IV typically leaks at least
  946%   _some_  information about  the  plaintext.   For example,  identical
  947%   plaintexts will  then correspond to identical  ciphertexts. For some
  948%   algorithms, reusing an  IV with the same Key  has disastrous results
  949%   and  can  cause  the  loss  of all  properties  that  are  otherwise
  950%   guaranteed.   Especially in  such  cases,  an IV  is  also called  a
  951%   _nonce_  (number used  once).   If  an IV  is  not  needed for  your
  952%   algorithm (such as =|'aes-128-ecb'|=) then any value can be provided
  953%   as it will  be ignored by the underlying  implementation.  Note that
  954%   such  algorithms do  not provide  _semantic security_  and are  thus
  955%   insecure. You should use stronger algorithms instead.
  956%
  957%   It is safe to store and  transfer the used initialization vector (or
  958%   nonce) in plain text, but the key _must be kept secret_.
  959%
  960%   Commonly used algorithms include:
  961%
  962%       $ =|'chacha20-poly1305'|= :
  963%       A powerful and efficient _authenticated_ encryption scheme,
  964%       providing secrecy and at the same time reliable protection
  965%       against undetected _modifications_ of the encrypted data. This
  966%       is a very good choice for virtually all use cases. It is a
  967%       _stream cipher_ and can encrypt data of any length up to 256 GB.
  968%       Further, the encrypted data has exactly the same length
  969%       as the original, and no padding is used. It requires OpenSSL
  970%       1.1.0 or greater. See below for an example.
  971%
  972%       $ =|'aes-128-gcm'|= :
  973%       Also an authenticated encryption scheme. It uses a 128-bit
  974%       (i.e., 16 bytes) key and a 96-bit (i.e., 12 bytes) nonce. It
  975%       requires OpenSSL 1.1.0 or greater.
  976%
  977%       $ =|'aes-128-cbc'|= :
  978%       A _block cipher_ that provides secrecy, but does not protect
  979%       against unintended modifications of the cipher text. This
  980%       algorithm uses 128-bit (16 bytes) keys and initialization
  981%       vectors.  It works with all supported versions of OpenSSL. If
  982%       possible, consider using an authenticated encryption scheme
  983%       instead.
  984%
  985%   Options:
  986%
  987%     - encoding(+Encoding)
  988%     Encoding to use for PlainText.  Default is `utf8`.  Alternatives
  989%     are `utf8` and `octet`.
  990%
  991%     - padding(+PaddingScheme)
  992%     For block ciphers, the padding scheme to use.  Default is
  993%     `block`.  You can disable padding by supplying `none` here. If
  994%     padding is disabled for block ciphers, then the length of the
  995%     ciphertext must be a multiple of the block size.
  996%
  997%     - tag(-List)
  998%     For authenticated encryption schemes, List is unified with a
  999%     list of _bytes_ holding the tag. This tag must be provided for
 1000%     decryption. Authenticated encryption requires OpenSSL 1.1.0 or
 1001%     greater.
 1002%
 1003%     - tag_length(+Length)
 1004%     For authenticated encryption schemes, the desired length of the
 1005%     tag, specified as the number of bytes.  The default is
 1006%     16. Smaller numbers are not recommended.
 1007%
 1008%   For example, with OpenSSL 1.1.0 and greater, we can use the ChaCha20
 1009%   stream cipher  with the Poly1305  authenticator. This cipher  uses a
 1010%   256-bit  key  and  a  96-bit  _nonce_,  i.e.,  32  and  12  _bytes_,
 1011%   respectively:
 1012%
 1013%     ```
 1014%     ?- Algorithm = 'chacha20-poly1305',
 1015%        crypto_n_random_bytes(32, Key),
 1016%        crypto_n_random_bytes(12, IV),
 1017%        crypto_data_encrypt("this is some input", Algorithm,
 1018%                    Key, IV, CipherText, [tag(Tag)]),
 1019%        crypto_data_decrypt(CipherText, Algorithm,
 1020%                    Key, IV, RecoveredText, [tag(Tag)]).
 1021%     Algorithm = 'chacha20-poly1305',
 1022%     Key = [65, 147, 140, 197, 27, 60, 198, 50, 218|...],
 1023%     IV = [253, 232, 174, 84, 168, 208, 218, 168, 228|...],
 1024%     CipherText = <binary string>,
 1025%     Tag = [248, 220, 46, 62, 255, 9, 178, 130, 250|...],
 1026%     RecoveredText = "this is some input".
 1027%     ```
 1028%
 1029%   In this  example, we use  crypto_n_random_bytes/2 to generate  a key
 1030%   and  nonce  from  cryptographically   secure  random  numbers.   For
 1031%   repeated applications,  you must  ensure that a  nonce is  only used
 1032%   _once_ together  with the same  key.  Note that  for _authenticated_
 1033%   encryption schemes, the _tag_ that was computed during encryption is
 1034%   necessary for decryption.  It is safe  to store and transfer the tag
 1035%   in plain text.
 1036%
 1037%   @see crypto_data_decrypt/6.
 1038%   @see hex_bytes/2 for conversion between bytes and hex encoding.
 1039
 1040crypto_data_encrypt(PlainText, Algorithm, Key, IV, CipherText, Options) :-
 1041        (   option(tag(AuthTag), Options) ->
 1042            option(tag_length(AuthLength), Options, 16)
 1043        ;   AuthTag = _,
 1044            AuthLength = -1
 1045        ),
 1046        '_crypto_data_encrypt'(PlainText, Algorithm, Key, IV,
 1047                               AuthLength, AuthTag, CipherText, Options).
 1048
 1049
 1050%%  crypto_modular_inverse(+X, +M, -Y) is det
 1051%
 1052%   Compute the modular multiplicative inverse of the integer X. Y is
 1053%   unified with an integer such that X*Y is congruent to 1 modulo M.
 1054
 1055
 1056crypto_modular_inverse(X, M, Y) :-
 1057    integer_serialized(X, XS),
 1058    integer_serialized(M, MS),
 1059    '_crypto_modular_inverse'(XS, MS, YHex),
 1060    hex_to_integer(YHex, Y).
 1061
 1062integer_serialized(I, serialized(S)) :-
 1063    must_be(integer, I),
 1064    integer_atomic_sign(I, Sign),
 1065    Abs is abs(I),
 1066    format(atom(A0), "~16r", [Abs]),
 1067    atom_length(A0, L),
 1068    Rem is L mod 2,
 1069    hex_pad(Rem, Sign, A0, S).
 1070
 1071integer_atomic_sign(I, S) :-
 1072    Sign is sign(I),
 1073    sign_atom(Sign, S).
 1074
 1075sign_atom(-1, '-').
 1076sign_atom( 0, '').
 1077sign_atom( 1, '').
 1078
 1079hex_pad(0, Sign, A0, A) :- atom_concat(Sign, A0, A).
 1080hex_pad(1, Sign, A0, A) :- atomic_list_concat([Sign,'0',A0], A).
 1081
 1082pow256(Byte, N0-I0, N-I) :-
 1083    N is N0 + Byte*256^I0,
 1084    I is I0 + 1.
 1085
 1086hex_to_integer(Hex, N) :-
 1087    hex_bytes(Hex, Bytes0),
 1088    reverse(Bytes0, Bytes),
 1089    foldl(pow256, Bytes, 0-0, N-_).
 1090
 1091%%  crypto_generate_prime(+N, -P, +Options) is det
 1092%
 1093%   Generate a prime P with at least N bits. Options is a list of options.
 1094%   Currently, the only supported option is:
 1095%
 1096%   * safe(Boolean)
 1097%     If `Boolean` is `true` (default is `false`), then a _safe_ prime
 1098%     is generated. This means that P is of the form 2*Q + 1 where Q
 1099%     is also prime.
 1100
 1101crypto_generate_prime(Bits, P, Options) :-
 1102        must_be(list, Options),
 1103        option(safe(Safe), Options, false),
 1104        '_crypto_generate_prime'(Bits, Hex, Safe, Options),
 1105        hex_to_integer(Hex, P).
 1106
 1107%%  crypto_is_prime(+P, +Options) is semidet
 1108%
 1109%   True iff P passes a probabilistic primality test. Options is a
 1110%   list of options. Currently, the only supported option is:
 1111%
 1112%   * iterations(N)
 1113%     N is the number of iterations that are performed. If this option
 1114%     is not specified, a number of iterations is used such that the
 1115%     probability of a false positive is at most 2^(-80).
 1116
 1117crypto_is_prime(P0, Options) :-
 1118        must_be(integer, P0),
 1119        must_be(list, Options),
 1120        option(iterations(N), Options, -1),
 1121        integer_serialized(P0, P),
 1122        '_crypto_is_prime'(P, N).
 1123
 1124%%  crypto_name_curve(+Name, -Curve) is det
 1125%
 1126%   Obtain a handle for a _named_ elliptic curve. Name is an atom, and
 1127%   Curve is unified with an opaque object that represents the curve.
 1128%   Currently, only elliptic curves over prime fields are
 1129%   supported. Examples of such curves are `prime256v1` and
 1130%   `secp256k1`.
 1131%
 1132%   If you have OpenSSL installed, you can get a list of supported
 1133%   curves via:
 1134%
 1135%   ==
 1136%   $ openssl ecparam -list_curves
 1137%   ==
 1138
 1139%%  crypto_curve_order(+Curve, -Order) is det
 1140%
 1141%   Obtain the order of an elliptic curve. Order is an integer,
 1142%   denoting how many points on the curve can be reached by
 1143%   multiplying the curve's generator with a scalar.
 1144
 1145crypto_curve_order(Curve, Order) :-
 1146    '_crypto_curve_order'(Curve, Hex),
 1147    hex_to_integer(Hex, Order).
 1148
 1149
 1150%%  crypto_curve_generator(+Curve, -Point) is det
 1151%
 1152%   Point is the _generator_ of the elliptic curve Curve.
 1153
 1154crypto_curve_generator(Curve, point(X,Y)) :-
 1155    '_crypto_curve_generator'(Curve, X0, Y0),
 1156    hex_to_integer(X0, X),
 1157    hex_to_integer(Y0, Y).
 1158
 1159%% crypto_curve_scalar_mult(+Curve, +N, +Point, -R) is det
 1160%
 1161%  R is the result of N times Point on the elliptic curve Curve. N
 1162%  must be an integer, and Point must be a point on the curve.
 1163
 1164crypto_curve_scalar_mult(Curve, S0, point(X0,Y0), point(A,B)) :-
 1165    maplist(integer_serialized, [S0,X0,Y0], [S,X,Y]),
 1166    '_crypto_curve_scalar_mult'(Curve, S, X, Y, A0, B0),
 1167    hex_to_integer(A0, A),
 1168    hex_to_integer(B0, B).
 1169
 1170
 1171                 /*******************************
 1172                 *          Sandboxing          *
 1173                 *******************************/
 1174
 1175:- multifile sandbox:safe_primitive/1. 1176
 1177sandbox:safe_primitive(crypto:hex_bytes(_,_)).
 1178sandbox:safe_primitive(crypto:crypto_n_random_bytes(_,_)).
 1179
 1180sandbox:safe_primitive(crypto:crypto_data_hash(_,_,_)).
 1181sandbox:safe_primitive(crypto:crypto_data_context(_,_,_)).
 1182sandbox:safe_primitive(crypto:crypto_context_new(_,_)).
 1183sandbox:safe_primitive(crypto:crypto_context_hash(_,_)).
 1184
 1185sandbox:safe_primitive(crypto:crypto_password_hash(_,_)).
 1186sandbox:safe_primitive(crypto:crypto_password_hash(_,_,_)).
 1187sandbox:safe_primitive(crypto:crypto_data_hkdf(_,_,_,_)).
 1188
 1189sandbox:safe_primitive(crypto:ecdsa_sign(_,_,_,_)).
 1190sandbox:safe_primitive(crypto:ecdsa_verify(_,_,_,_)).
 1191
 1192sandbox:safe_primitive(crypto:ed25519_new_keypair(_)).
 1193sandbox:safe_primitive(crypto:ed25519_seed_keypair(_,_)).
 1194sandbox:safe_primitive(crypto:ed25519_keypair_public_key(_,_)).
 1195sandbox:safe_primitive(crypto:ed25519_sign(_,_,_,_)).
 1196sandbox:safe_primitive(crypto:ed25519_verify(_,_,_,_)).
 1197
 1198sandbox:safe_primitive(crypto:curve25519_generator(_)).
 1199sandbox:safe_primitive(crypto:curve25519_scalar_mult(_,_,_)).
 1200
 1201sandbox:safe_primitive(crypto:rsa_sign(_,_,_,_)).
 1202sandbox:safe_primitive(crypto:rsa_verify(_,_,_,_)).
 1203sandbox:safe_primitive(crypto:rsa_public_encrypt(_,_,_,_)).
 1204sandbox:safe_primitive(crypto:rsa_public_decrypt(_,_,_,_)).
 1205sandbox:safe_primitive(crypto:rsa_private_encrypt(_,_,_,_)).
 1206sandbox:safe_primitive(crypto:rsa_private_decrypt(_,_,_,_)).
 1207
 1208sandbox:safe_primitive(crypto:crypto_data_decrypt(_,_,_,_,_,_)).
 1209sandbox:safe_primitive(crypto:crypto_data_encrypt(_,_,_,_,_,_)).
 1210
 1211sandbox:safe_primitive(crypto:crypto_modular_inverse(_,_,_)).
 1212sandbox:safe_primitive(crypto:crypto_generate_prime(_,_,_)).
 1213sandbox:safe_primitive(crypto:crypto_is_prime(_,_)).
 1214
 1215sandbox:safe_primitive(crypto:crypto_name_curve(_,_)).
 1216sandbox:safe_primitive(crypto:crypto_curve_order(_,_)).
 1217sandbox:safe_primitive(crypto:crypto_curve_generator(_,_)).
 1218sandbox:safe_primitive(crypto:crypto_curve_scalar_mult(_,_,_,_)).
 1219
 1220                 /*******************************
 1221                 *           MESSAGES           *
 1222                 *******************************/
 1223
 1224:- multifile
 1225    prolog:error_message//1. 1226
 1227prolog:error_message(ssl_error(ID, _Library, Function, Reason)) -->
 1228    [ 'SSL(~w) ~w: ~w'-[ID, Function, Reason] ]