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