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