1Public Key Cryptography
2=================================
3
4Public key cryptography (also called asymmetric cryptography) is a collection
5of techniques allowing for encryption, signatures, and key agreement.
6
7Key Objects
8----------------------------------------
9
10Public and private keys are represented by classes ``Public_Key`` and it's
11subclass ``Private_Key``. The use of inheritance here means that a
12``Private_Key`` can be converted into a reference to a public key.
13
14None of the functions on ``Public_Key`` and ``Private_Key`` itself are
15particularly useful for users of the library, because 'bare' public key
16operations are *very insecure*. The only purpose of these functions is to
17provide a clean interface that higher level operations can be built on. So
18really the only thing you need to know is that when a function takes a
19reference to a ``Public_Key``, it can take any public key or private key, and
20similarly for ``Private_Key``.
21
22Types of ``Public_Key`` include ``RSA_PublicKey``, ``DSA_PublicKey``,
23``ECDSA_PublicKey``, ``ECKCDSA_PublicKey``, ``ECGDSA_PublicKey``, ``DH_PublicKey``, ``ECDH_PublicKey``,
24``Curve25519_PublicKey``, ``ElGamal_PublicKey``, ``McEliece_PublicKey``, ``XMSS_PublicKey``
25and ``GOST_3410_PublicKey``.  There are corresponding ``Private_Key`` classes for each of these algorithms.
26
27.. _creating_new_private_keys:
28
29Creating New Private Keys
30----------------------------------------
31
32Creating a new private key requires two things: a source of random numbers
33(see :ref:`random_number_generators`) and some algorithm specific parameters
34that define the *security level* of the resulting key. For instance, the
35security level of an RSA key is (at least in part) defined by the length of
36the public key modulus in bits. So to create a new RSA private key, you would
37call
38
39.. cpp:function:: RSA_PrivateKey::RSA_PrivateKey(RandomNumberGenerator& rng, size_t bits)
40
41  A constructor that creates a new random RSA private key with a modulus
42  of length *bits*.
43
44  RSA key generation is relatively slow, and can take an unpredictable
45  amount of time. Generating a 2048 bit RSA key might take 5 to 10
46  seconds on a slow machine like a Raspberry Pi 2. Even on a fast
47  desktop it might take up to half a second. In a GUI blocking for
48  that long can be a problem. The usual approach is to perform key
49  generation in a new thread, with a animated modal UI element so the
50  user knows the application is still alive. If you wish to provide a
51  progress estimate things get a bit complicated but some library
52  users documented their approach in
53  `a blog post <https://medium.com/nexenio/indicating-progress-of-rsa-key-pair-generation-the-practical-approach-a049ba829dbe>`_.
54
55Algorithms based on the discrete-logarithm problem use what is called a
56*group*; a group can safely be used with many keys, and for some operations,
57like key agreement, the two keys *must* use the same group.  There are
58currently two kinds of discrete logarithm groups supported in botan: the
59integers modulo a prime, represented by :ref:`dl_group`, and elliptic curves
60in GF(p), represented by :ref:`ec_group`. A rough generalization is that the
61larger the group is, the more secure the algorithm is, but correspondingly the
62slower the operations will be.
63
64Given a ``DL_Group``, you can create new DSA, Diffie-Hellman and ElGamal key pairs with
65
66.. cpp:function:: DSA_PrivateKey::DSA_PrivateKey(RandomNumberGenerator& rng, \
67   const DL_Group& group, const BigInt& x = 0)
68
69.. cpp:function:: DH_PrivateKey::DH_PrivateKey(RandomNumberGenerator& rng, \
70   const DL_Group& group, const BigInt& x = 0)
71
72.. cpp:function:: ElGamal_PrivateKey::ElGamal_PrivateKey(RandomNumberGenerator& rng, \
73   const DL_Group& group, const BigInt& x = 0)
74
75  The optional *x* parameter to each of these constructors is a private key
76  value. This allows you to create keys where the private key is formed by
77  some special technique; for instance you can use the hash of a password (see
78  :ref:`pbkdf` for how to do that) as a private key value. Normally, you would
79  leave the value as zero, letting the class generate a new random key.
80
81Finally, given an ``EC_Group`` object, you can create a new ECDSA, ECKCDSA, ECGDSA,
82ECDH, or GOST 34.10-2001 private key with
83
84.. cpp:function:: ECDSA_PrivateKey::ECDSA_PrivateKey(RandomNumberGenerator& rng, \
85   const EC_Group& domain, const BigInt& x = 0)
86
87.. cpp:function:: ECKCDSA_PrivateKey::ECKCDSA_PrivateKey(RandomNumberGenerator& rng, \
88      const EC_Group& domain, const BigInt& x = 0)
89
90.. cpp:function:: ECGDSA_PrivateKey::ECGDSA_PrivateKey(RandomNumberGenerator& rng, \
91   const EC_Group& domain, const BigInt& x = 0)
92
93.. cpp:function:: ECDH_PrivateKey::ECDH_PrivateKey(RandomNumberGenerator& rng, \
94   const EC_Group& domain, const BigInt& x = 0)
95
96.. cpp:function:: GOST_3410_PrivateKey::GOST_3410_PrivateKey(RandomNumberGenerator& rng, \
97   const EC_Group& domain, const BigInt& x = 0)
98
99.. _serializing_private_keys:
100
101Serializing Private Keys Using PKCS #8
102----------------------------------------
103
104The standard format for serializing a private key is PKCS #8, the operations
105for which are defined in ``pkcs8.h``. It supports both unencrypted and
106encrypted storage.
107
108.. cpp:function:: secure_vector<uint8_t> PKCS8::BER_encode(const Private_Key& key, \
109   RandomNumberGenerator& rng, const std::string& password, const std::string& pbe_algo = "")
110
111  Takes any private key object, serializes it, encrypts it using
112  *password*, and returns a binary structure representing the private
113  key.
114
115  The final (optional) argument, *pbe_algo*, specifies a particular
116  password based encryption (or PBE) algorithm. If you don't specify a
117  PBE, a sensible default will be used.
118
119  The currently supported PBE is PBES2 from PKCS5. Format is as follows:
120  ``PBE-PKCS5v20(CIPHER,PBKDF)``. Since 2.8.0, ``PBES2(CIPHER,PBKDF)`` also works.
121  Cipher can be any block cipher with /CBC or /GCM appended, for example
122  "AES-128/CBC" or "Camellia-256/GCM". For best interop with other systems, use
123  AES in CBC mode. The PBKDF can be either the name of a hash function (in which
124  case PBKDF2 is used with that hash) or "Scrypt", which causes the scrypt
125  memory hard password hashing function to be used. Scrypt is supported since
126  version 2.7.0.
127
128  Use `PBE-PKCS5v20(AES-256/CBC,SHA-256)` if you want to ensure the keys can
129  be imported by different software packages. Use
130  `PBE-PKCS5v20(AES-256/GCM,Scrypt)` for best security assuming you do not
131  care about interop.
132
133  For ciphers you can use anything which has an OID defined for CBC, GCM or SIV
134  modes. Currently this includes AES, Camellia, Serpent, Twofish, and SM4. Most
135  other libraries only support CBC mode for private key encryption. GCM has
136  been supported in PBES2 since 1.11.10. SIV has been supported since 2.8.
137
138.. cpp:function:: std::string PKCS8::PEM_encode(const Private_Key& key, \
139   RandomNumberGenerator& rng, const std::string& pass, const std::string& pbe_algo = "")
140
141  This formats the key in the same manner as ``BER_encode``, but additionally
142  encodes it into a text format with identifying headers. Using PEM encoding
143  is *highly* recommended for many reasons, including compatibility with other
144  software, for transmission over 8-bit unclean channels, because it can be
145  identified by a human without special tools, and because it sometimes allows
146  more sane behavior of tools that process the data.
147
148Unencrypted serialization is also supported.
149
150.. warning::
151
152  In most situations, using unencrypted private key storage is a bad idea,
153  because anyone can come along and grab the private key without having to
154  know any passwords or other secrets. Unless you have very particular
155  security requirements, always use the versions that encrypt the key based on
156  a passphrase, described above.
157
158.. cpp:function:: secure_vector<uint8_t> PKCS8::BER_encode(const Private_Key& key)
159
160  Serializes the private key and returns the result.
161
162.. cpp:function:: std::string PKCS8::PEM_encode(const Private_Key& key)
163
164  Serializes the private key, base64 encodes it, and returns the
165  result.
166
167Last but not least, there are some functions that will load (and
168decrypt, if necessary) a PKCS #8 private key:
169
170.. cpp:function:: Private_Key* PKCS8::load_key(DataSource& in, \
171   RandomNumberGenerator& rng, const User_Interface& ui)
172
173.. cpp:function:: Private_Key* PKCS8::load_key(DataSource& in, \
174   RandomNumberGenerator& rng, std::string passphrase = "")
175
176.. cpp:function:: Private_Key* PKCS8::load_key(const std::string& filename, \
177   RandomNumberGenerator& rng, const User_Interface& ui)
178
179.. cpp:function:: Private_Key* PKCS8::load_key(const std::string& filename, \
180   RandomNumberGenerator& rng, const std::string& passphrase = "")
181
182These functions will return an object allocated key object based on the data
183from whatever source it is using (assuming, of course, the source is in fact
184storing a representation of a private key, and the decryption was
185successful). The encoding used (PEM or BER) need not be specified; the format
186will be detected automatically. The key is allocated with ``new``, and should
187be released with ``delete`` when you are done with it. The first takes a
188generic ``DataSource`` that you have to create - the other is a simple wrapper
189functions that take either a filename or a memory buffer and create the
190appropriate ``DataSource``.
191
192The versions taking a ``std::string`` attempt to decrypt using the password
193given (if the key is encrypted; if it is not, the passphase value will be
194ignored). If the passphrase does not decrypt the key, an exception will be
195thrown.
196
197The ones taking a ``User_Interface`` provide a simple callback interface which
198makes handling incorrect passphrases and such a bit simpler. A
199``User_Interface`` has very little to do with talking to users; it's just a
200way to glue together Botan and whatever user interface you happen to be using.
201
202.. note::
203
204  In a future version, it is likely that ``User_Interface`` will be
205  replaced by a simple callback using ``std::function``.
206
207To use ``User_Interface``, derive a subclass and implement:
208
209.. cpp:function:: std::string User_Interface::get_passphrase(const std::string& what, \
210   const std::string& source, UI_Result& result) const
211
212  The ``what`` argument specifies what the passphrase is needed for (for
213  example, PKCS #8 key loading passes ``what`` as "PKCS #8 private key"). This
214  lets you provide the user with some indication of *why* your application is
215  asking for a passphrase; feel free to pass the string through ``gettext(3)``
216  or moral equivalent for i18n purposes. Similarly, ``source`` specifies where
217  the data in question came from, if available (for example, a file name). If
218  the source is not available for whatever reason, then ``source`` will be an
219  empty string; be sure to account for this possibility.
220
221  The function returns the passphrase as the return value, and a status code
222  in ``result`` (either ``OK`` or ``CANCEL_ACTION``). If ``CANCEL_ACTION`` is
223  returned in ``result``, then the return value will be ignored, and the
224  caller will take whatever action is necessary (typically, throwing an
225  exception stating that the passphrase couldn't be determined). In the
226  specific case of PKCS #8 key decryption, a ``Decoding_Error`` exception will
227  be thrown; your UI should assume this can happen, and provide appropriate
228  error handling (such as putting up a dialog box informing the user of the
229  situation, and canceling the operation in progress).
230
231.. _serializing_public_keys:
232
233Serializing Public Keys
234^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
235
236To import and export public keys, use:
237
238.. cpp:function:: std::vector<uint8_t> X509::BER_encode(const Public_Key& key)
239
240.. cpp:function:: std::string X509::PEM_encode(const Public_Key& key)
241
242.. cpp:function:: Public_Key* X509::load_key(DataSource& in)
243
244.. cpp:function:: Public_Key* X509::load_key(const secure_vector<uint8_t>& buffer)
245
246.. cpp:function:: Public_Key* X509::load_key(const std::string& filename)
247
248  These functions operate in the same way as the ones described in
249  :ref:`serializing_private_keys`, except that no encryption option is
250  available.
251
252.. _dl_group:
253
254DL_Group
255^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
256
257As described in :ref:`creating_new_private_keys`, a discrete logarithm group
258can be shared among many keys, even keys created by users who do not trust
259each other. However, it is necessary to trust the entity who created the
260group; that is why organization like NIST use algorithms which generate groups
261in a deterministic way such that creating a bogus group would require breaking
262some trusted cryptographic primitive like SHA-2.
263
264Instantiating a ``DL_Group`` simply requires calling
265
266.. cpp:function:: DL_Group::DL_Group(const std::string& name)
267
268  The *name* parameter is a specially formatted string that consists of three
269  things, the type of the group ("modp" or "dsa"), the creator of the group,
270  and the size of the group in bits, all delimited by '/' characters.
271
272  Currently all "modp" groups included in botan are ones defined by the
273  Internet Engineering Task Force, so the provider is "ietf", and the strings
274  look like "modp/ietf/N" where N can be any of 1024, 1536, 2048, 3072,
275  4096, 6144, or 8192. This group type is used for Diffie-Hellman and ElGamal
276  algorithms.
277
278  The other type, "dsa" is used for DSA keys. They can also be used with
279  Diffie-Hellman and ElGamal, but this is less common. The currently available
280  groups are "dsa/jce/1024" and "dsa/botan/N" with N being 2048 or 3072.  The
281  "jce" groups are the standard DSA groups used in the Java Cryptography
282  Extensions, while the "botan" groups were randomly generated using the
283  FIPS 186-3 algorithm by the library maintainers.
284
285You can generate a new random group using
286
287.. cpp:function:: DL_Group::DL_Group(RandomNumberGenerator& rng, \
288   PrimeType type, size_t pbits, size_t qbits = 0)
289
290  The *type* can be either ``Strong``, ``Prime_Subgroup``, or
291  ``DSA_Kosherizer``. *pbits* specifies the size of the prime in
292  bits. If the *type* is ``Prime_Subgroup`` or ``DSA_Kosherizer``,
293  then *qbits* specifies the size of the subgroup.
294
295You can serialize a ``DL_Group`` using
296
297.. cpp:function:: secure_vector<uint8_t> DL_Group::DER_Encode(Format format)
298
299or
300
301.. cpp:function:: std::string DL_Group::PEM_encode(Format format)
302
303where *format* is any of
304
305* ``ANSI_X9_42`` (or ``DH_PARAMETERS``) for modp groups
306* ``ANSI_X9_57`` (or ``DSA_PARAMETERS``) for DSA-style groups
307* ``PKCS_3`` is an older format for modp groups; it should only
308  be used for backwards compatibility.
309
310You can reload a serialized group using
311
312.. cpp:function:: void DL_Group::BER_decode(DataSource& source, Format format)
313
314.. cpp:function:: void DL_Group::PEM_decode(DataSource& source)
315
316Code Example
317"""""""""""""""""
318The example below creates a new 2048 bit ``DL_Group``, prints the generated
319parameters and ANSI_X9_42 encodes the created group for further usage with DH.
320
321.. code-block:: cpp
322
323    #include <botan/dl_group.h>
324    #include <botan/auto_rng.h>
325    #include <botan/rng.h>
326    #include <iostream>
327
328    int main()
329       {
330    	  std::unique_ptr<Botan::RandomNumberGenerator> rng(new Botan::AutoSeeded_RNG);
331    	  std::unique_ptr<Botan::DL_Group> group(new Botan::DL_Group(*rng.get(), Botan::DL_Group::Strong, 2048));
332    	  std::cout << std::endl << "p: " << group->get_p();
333    	  std::cout << std::endl << "q: " << group->get_q();
334    	  std::cout << std::endl << "g: " << group->get_q();
335    	  std::cout << std::endl << "ANSI_X9_42: " << std::endl << group->PEM_encode(Botan::DL_Group::ANSI_X9_42);
336
337        return 0;
338       }
339
340
341.. _ec_group:
342
343EC_Group
344^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
345
346An ``EC_Group`` is initialized by passing the name of the
347group to be used to the constructor. These groups have
348semi-standardized names like "secp256r1" and "brainpool512r1".
349
350Key Checking
351---------------------------------
352
353Most public key algorithms have limitations or restrictions on their
354parameters. For example RSA requires an odd exponent, and algorithms
355based on the discrete logarithm problem need a generator > 1.
356
357Each public key type has a function
358
359.. cpp:function:: bool Public_Key::check_key(RandomNumberGenerator& rng, bool strong)
360
361  This function performs a number of algorithm-specific tests that the key
362  seems to be mathematically valid and consistent, and returns true if all of
363  the tests pass.
364
365  It does not have anything to do with the validity of the key for any
366  particular use, nor does it have anything to do with certificates that link
367  a key (which, after all, is just some numbers) with a user or other
368  entity. If *strong* is ``true``, then it does "strong" checking, which
369  includes expensive operations like primality checking.
370
371As key checks are not automatically performed they must be called
372manually after loading keys from untrusted sources. If a key from an untrusted source
373is not checked, the implementation might be vulnerable to algorithm specific attacks.
374
375The following example loads the Subject Public Key from the x509 certificate ``cert.pem`` and checks the
376loaded key. If the key check fails a respective error is thrown.
377
378.. code-block:: cpp
379
380    #include <botan/x509cert.h>
381    #include <botan/auto_rng.h>
382    #include <botan/rng.h>
383
384    int main()
385       {
386       Botan::X509_Certificate cert("cert.pem");
387       std::unique_ptr<Botan::RandomNumberGenerator> rng(new Botan::AutoSeeded_RNG);
388       std::unique_ptr<Botan::Public_Key> key(cert.subject_public_key());
389       if(!key->check_key(*rng.get(), false))
390          {
391          throw std::invalid_argument("Loaded key is invalid");
392          }
393       }
394
395Encryption
396---------------------------------
397
398Safe public key encryption requires the use of a padding scheme which hides
399the underlying mathematical properties of the algorithm.  Additionally, they
400will add randomness, so encrypting the same plaintext twice produces two
401different ciphertexts.
402
403The primary interface for encryption is
404
405.. cpp:class:: PK_Encryptor
406
407   .. cpp:function:: secure_vector<uint8_t> encrypt( \
408         const uint8_t* in, size_t length, RandomNumberGenerator& rng) const
409
410   .. cpp:function:: secure_vector<uint8_t> encrypt( \
411      const std::vector<uint8_t>& in, RandomNumberGenerator& rng) const
412
413      These encrypt a message, returning the ciphertext.
414
415   .. cpp:function::  size_t maximum_input_size() const
416
417      Returns the maximum size of the message that can be processed, in
418      bytes. If you call :cpp:func:`PK_Encryptor::encrypt` with a value larger
419      than this the operation will fail with an exception.
420
421:cpp:class:`PK_Encryptor` is only an interface - to actually encrypt you have
422to create an implementation, of which there are currently three available in the
423library, :cpp:class:`PK_Encryptor_EME`, :cpp:class:`DLIES_Encryptor` and
424:cpp:class:`ECIES_Encryptor`. DLIES is a hybrid encryption scheme (from
425IEEE 1363) that uses the DH key agreement technique in combination with a KDF, a
426MAC and a symmetric encryption algorithm to perform message encryption. ECIES is
427similar to DLIES, but uses ECDH for the key agreement. Normally, public key
428encryption is done using algorithms which support it directly, such as RSA or
429ElGamal; these use the EME class:
430
431.. cpp:class:: PK_Encryptor_EME
432
433   .. cpp:function:: PK_Encryptor_EME(const Public_Key& key, std::string eme)
434
435     With *key* being the key you want to encrypt messages to. The padding
436     method to use is specified in *eme*.
437
438     The recommended values for *eme* is "EME1(SHA-1)" or "EME1(SHA-256)". If
439     you need compatibility with protocols using the PKCS #1 v1.5 standard,
440     you can also use "EME-PKCS1-v1_5".
441
442.. cpp:class:: DLIES_Encryptor
443
444   Available in the header ``dlies.h``
445
446   .. cpp:function:: DLIES_Encryptor(const DH_PrivateKey& own_priv_key, \
447         RandomNumberGenerator& rng, KDF* kdf, MessageAuthenticationCode* mac, \
448         size_t mac_key_len = 20)
449
450      Where *kdf* is a key derivation function (see
451      :ref:`key_derivation_function`) and *mac* is a
452      MessageAuthenticationCode. The encryption is performed by XORing the
453      message with a stream of bytes provided by the KDF.
454
455   .. cpp:function:: DLIES_Encryptor(const DH_PrivateKey& own_priv_key, \
456         RandomNumberGenerator& rng, KDF* kdf, Cipher_Mode* cipher, \
457         size_t cipher_key_len, MessageAuthenticationCode* mac, \
458         size_t mac_key_len = 20)
459
460      Instead of XORing the message a block cipher can be specified.
461
462.. cpp:class:: ECIES_Encryptor
463
464   Available in the header ``ecies.h``.
465
466   Parameters for encryption and decryption are set by the
467   :cpp:class:`ECIES_System_Params` class which stores the EC domain parameters,
468   the KDF (see :ref:`key_derivation_function`), the cipher (see
469   :ref:`cipher_modes`) and the MAC.
470
471   .. cpp:function:: ECIES_Encryptor(const PK_Key_Agreement_Key& private_key, \
472         const ECIES_System_Params& ecies_params, \
473         RandomNumberGenerator& rng)
474
475      Where *private_key* is the key to use for the key agreement. The system
476      parameters are specified in *ecies_params* and the RNG to use is passed in
477      *rng*.
478
479   .. cpp:function:: ECIES_Encryptor(RandomNumberGenerator& rng, \
480         const ECIES_System_Params& ecies_params)
481
482      Creates an ephemeral private key which is used for the key agreement.
483
484The decryption classes are named :cpp:class:`PK_Decryptor`,
485:cpp:class:`PK_Decryptor_EME`, :cpp:class:`DLIES_Decryptor` and
486:cpp:class:`ECIES_Decryptor`. They are created in the exact same way, except
487they take the private key, and the processing function is named ``decrypt``.
488
489
490Botan implements the following encryption algorithms and padding schemes:
491
4921. RSA
493    - "PKCS1v15" || "EME-PKCS1-v1_5"
494    - "OAEP" || "EME-OAEP" || "EME1" || "EME1(SHA-1)" || "EME1(SHA-256)"
495#. DLIES
496#. ECIES
497#. SM2
498
499Code Example
500^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
501The following Code sample reads a PKCS #8 keypair from the passed location and
502subsequently encrypts a fixed plaintext with the included public key, using EME1
503with SHA-256. For the sake of completeness, the ciphertext is then decrypted using
504the private key.
505
506.. code-block:: cpp
507
508  #include <botan/pkcs8.h>
509  #include <botan/hex.h>
510  #include <botan/pk_keys.h>
511  #include <botan/pubkey.h>
512  #include <botan/auto_rng.h>
513  #include <botan/rng.h>
514  #include <iostream>
515  int main (int argc, char* argv[])
516    {
517    if(argc!=2)
518       return 1;
519    std::string plaintext("Your great-grandfather gave this watch to your granddad for good luck. Unfortunately, Dane's luck wasn't as good as his old man's.");
520    std::vector<uint8_t> pt(plaintext.data(),plaintext.data()+plaintext.length());
521    std::unique_ptr<Botan::RandomNumberGenerator> rng(new Botan::AutoSeeded_RNG);
522
523    //load keypair
524    std::unique_ptr<Botan::Private_Key> kp(Botan::PKCS8::load_key(argv[1],*rng.get()));
525
526    //encrypt with pk
527    Botan::PK_Encryptor_EME enc(*kp,*rng.get(), "EME1(SHA-256)");
528    std::vector<uint8_t> ct = enc.encrypt(pt,*rng.get());
529
530    //decrypt with sk
531    Botan::PK_Decryptor_EME dec(*kp,*rng.get(), "EME1(SHA-256)");
532    std::cout << std::endl << "enc: " << Botan::hex_encode(ct) << std::endl << "dec: "<< Botan::hex_encode(dec.decrypt(ct));
533
534    return 0;
535    }
536
537
538Signatures
539---------------------------------
540
541Signature generation is performed using
542
543.. cpp:class:: PK_Signer
544
545   .. cpp:function:: PK_Signer(const Private_Key& key, \
546      const std::string& emsa, \
547      Signature_Format format = IEEE_1363)
548
549     Constructs a new signer object for the private key *key* using the
550     signature format *emsa*. The key must support signature operations.  In
551     the current version of the library, this includes RSA, DSA, ECDSA, ECKCDSA,
552     ECGDSA, GOST 34.10-2001. Other signature schemes may be supported in the future.
553
554     .. note::
555
556       Botan both supports non-deterministic and deterministic (as per RFC
557       6979) DSA and ECDSA signatures. Deterministic signatures are compatible
558       in the way that they can be verified with a non-deterministic implementation.
559       If the ``rfc6979`` module is enabled, deterministic DSA and ECDSA signatures
560       will be generated.
561
562     Currently available values for *emsa* include EMSA1, EMSA2, EMSA3, EMSA4,
563     and Raw. All of them, except Raw, take a parameter naming a message
564     digest function to hash the message with. The Raw encoding signs the
565     input directly; if the message is too big, the signing operation will
566     fail. Raw is not useful except in very specialized applications. Examples
567     are "EMSA1(SHA-1)" and "EMSA4(SHA-256)".
568
569     For RSA, use EMSA4 (also called PSS) unless you need compatibility with
570     software that uses the older PKCS #1 v1.5 standard, in which case use
571     EMSA3 (also called "EMSA-PKCS1-v1_5"). For DSA, ECDSA, ECKCDSA, ECGDSA and
572     GOST 34.10-2001 you should use EMSA1.
573
574     The *format* defaults to ``IEEE_1363`` which is the only available
575     format for RSA. For DSA, ECDSA, ECGDSA and ECKCDSA you can also use
576     ``DER_SEQUENCE``, which will format the signature as an ASN.1
577     SEQUENCE value.
578
579   .. cpp:function:: void update(const uint8_t* in, size_t length)
580   .. cpp:function:: void update(const std::vector<uint8_t>& in)
581   .. cpp:function:: void update(uint8_t in)
582
583      These add more data to be included in the signature
584      computation. Typically, the input will be provided directly to a
585      hash function.
586
587   .. cpp:function:: secure_vector<uint8_t> signature(RandomNumberGenerator& rng)
588
589      Creates the signature and returns it
590
591   .. cpp:function:: secure_vector<uint8_t> sign_message( \
592      const uint8_t* in, size_t length, RandomNumberGenerator& rng)
593
594   .. cpp:function:: secure_vector<uint8_t> sign_message( \
595      const std::vector<uint8_t>& in, RandomNumberGenerator& rng)
596
597      These functions are equivalent to calling
598      :cpp:func:`PK_Signer::update` and then
599      :cpp:func:`PK_Signer::signature`. Any data previously provided
600      using ``update`` will be included.
601
602Signatures are verified using
603
604.. cpp:class:: PK_Verifier
605
606   .. cpp:function:: PK_Verifier(const Public_Key& pub_key, \
607          const std::string& emsa, Signature_Format format = IEEE_1363)
608
609      Construct a new verifier for signatures associated with public
610      key *pub_key*. The *emsa* and *format* should be the same as
611      that used by the signer.
612
613   .. cpp:function:: void update(const uint8_t* in, size_t length)
614   .. cpp:function:: void update(const std::vector<uint8_t>& in)
615   .. cpp:function:: void update(uint8_t in)
616
617      Add further message data that is purportedly associated with the
618      signature that will be checked.
619
620   .. cpp:function:: bool check_signature(const uint8_t* sig, size_t length)
621   .. cpp:function:: bool check_signature(const std::vector<uint8_t>& sig)
622
623      Check to see if *sig* is a valid signature for the message data
624      that was written in. Return true if so. This function clears the
625      internal message state, so after this call you can call
626      :cpp:func:`PK_Verifier::update` to start verifying another
627      message.
628
629   .. cpp:function:: bool verify_message(const uint8_t* msg, size_t msg_length, \
630                                         const uint8_t* sig, size_t sig_length)
631
632   .. cpp:function:: bool verify_message(const std::vector<uint8_t>& msg, \
633                                         const std::vector<uint8_t>& sig)
634
635      These are equivalent to calling :cpp:func:`PK_Verifier::update`
636      on *msg* and then calling :cpp:func:`PK_Verifier::check_signature`
637      on *sig*.
638
639
640Botan implements the following signature algorithms:
641
6421. RSA
643#. DSA
644#. ECDSA
645#. ECGDSA
646#. ECKDSA
647#. GOST 34.10-2001
648#. Ed25519
649#. SM2
650
651Code Example
652^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
653
654The following sample program below demonstrates the generation of a new ECDSA keypair over the curve secp512r1
655and a ECDSA signature using EMSA1 with SHA-256. Subsequently the computed signature is validated.
656
657.. code-block:: cpp
658
659  #include <botan/auto_rng.h>
660  #include <botan/ecdsa.h>
661  #include <botan/ec_group.h>
662  #include <botan/pubkey.h>
663  #include <botan/hex.h>
664  #include <iostream>
665
666  int main()
667    {
668    Botan::AutoSeeded_RNG rng;
669    // Generate ECDSA keypair
670    Botan::ECDSA_PrivateKey key(rng, Botan::EC_Group("secp521r1"));
671
672    std::string text("This is a tasty burger!");
673    std::vector<uint8_t> data(text.data(),text.data()+text.length());
674    // sign data
675    Botan::PK_Signer signer(key, rng, "EMSA1(SHA-256)");
676    signer.update(data);
677    std::vector<uint8_t> signature = signer.signature(rng);
678    std::cout << "Signature:" << std::endl << Botan::hex_encode(signature);
679    // verify signature
680    Botan::PK_Verifier verifier(key, "EMSA1(SHA-256)");
681    verifier.update(data);
682    std::cout << std::endl << "is " << (verifier.check_signature(signature)? "valid" : "invalid");
683    return 0;
684    }
685
686
687Ed25519 Variants
688^^^^^^^^^^^^^^^^^^
689
690Most signature schemes in Botan follow a hash-then-sign paradigm. That is, the
691entire message is digested to a fixed length representative using a collision
692resistant hash function, and then the digest is signed. Ed25519 instead signs
693the message directly. This is beneficial, in that the Ed25519 design should
694remain secure even in the (extremely unlikely) event that a collision attack on
695SHA-512 is found. However it means the entire message must be buffered in
696memory, which can be a problem for many applications which might need to sign
697large inputs. To use this variety of Ed25519, use a padding name of "Pure".
698
699Ed25519ph (pre-hashed) instead hashes the message with SHA-512 and then signs
700the digest plus a special prefix specified in RFC 8032. To use it, specify
701padding name "Ed25519ph".
702
703Another variant of pre-hashing is used by GnuPG. There the message is digested
704with any hash function, then the digest is signed. To use it, specify any valid
705hash function. Even if SHA-512 is used, this variant is not compatible with
706Ed25519ph.
707
708For best interop with other systems, prefer "Ed25519ph".
709
710Key Agreement
711---------------------------------
712
713You can get a hold of a ``PK_Key_Agreement_Scheme`` object by calling
714``get_pk_kas`` with a key that is of a type that supports key
715agreement (such as a Diffie-Hellman key stored in a ``DH_PrivateKey``
716object), and the name of a key derivation function. This can be "Raw",
717meaning the output of the primitive itself is returned as the key, or
718"KDF1(hash)" or "KDF2(hash)" where "hash" is any string you happen to
719like (hopefully you like strings like "SHA-256" or "RIPEMD-160"), or
720"X9.42-PRF(keywrap)", which uses the PRF specified in ANSI X9.42. It
721takes the name or OID of the key wrap algorithm that will be used to
722encrypt a content encryption key.
723
724How key agreement works is that you trade public values with some
725other party, and then each of you runs a computation with the other's
726value and your key (this should return the same result to both
727parties). This computation can be called by using
728``derive_key`` with either a byte array/length pair, or a
729``secure_vector<uint8_t>`` than holds the public value of the other
730party. The last argument to either call is a number that specifies how
731long a key you want.
732
733Depending on the KDF you're using, you *might not* get back a key
734of the size you requested. In particular "Raw" will return a number
735about the size of the Diffie-Hellman modulus, and KDF1 can only return
736a key that is the same size as the output of the hash. KDF2, on the
737other hand, will always give you a key exactly as long as you request,
738regardless of the underlying hash used with it. The key returned is a
739``SymmetricKey``, ready to pass to a block cipher, MAC, or other
740symmetric algorithm.
741
742The public value that should be used can be obtained by calling
743``public_data``, which exists for any key that is associated with a
744key agreement algorithm. It returns a ``secure_vector<uint8_t>``.
745
746"KDF2(SHA-256)" is by far the preferred algorithm for key derivation
747in new applications. The X9.42 algorithm may be useful in some
748circumstances, but unless you need X9.42 compatibility, KDF2 is easier
749to use.
750
751
752Botan implements the following key agreement methods:
753
7541. ECDH over GF(p) Weierstrass curves
755#. ECDH over x25519
756#. DH over prime fields
757#. McEliece
758#. NewHope
759
760Code Example
761^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
762
763The code below performs an unauthenticated ECDH key agreement using the secp521r elliptic curve and
764applies the key derivation function KDF2(SHA-256) with 256 bit output length to the computed shared secret.
765
766.. code-block:: cpp
767
768  #include <botan/auto_rng.h>
769  #include <botan/ecdh.h>
770  #include <botan/ec_group.h>
771  #include <botan/pubkey.h>
772  #include <botan/hex.h>
773  #include <iostream>
774
775  int main()
776     {
777     Botan::AutoSeeded_RNG rng;
778     // ec domain and
779     Botan::EC_Group domain("secp521r1");
780     std::string kdf = "KDF2(SHA-256)";
781     // generate ECDH keys
782     Botan::ECDH_PrivateKey keyA(rng, domain);
783     Botan::ECDH_PrivateKey keyB(rng, domain);
784     // Construct key agreements
785     Botan::PK_Key_Agreement ecdhA(keyA,rng,kdf);
786     Botan::PK_Key_Agreement ecdhB(keyB,rng,kdf);
787     // Agree on shared secret and derive symmetric key of 256 bit length
788     Botan::secure_vector<uint8_t> sA = ecdhA.derive_key(32,keyB.public_value()).bits_of();
789     Botan::secure_vector<uint8_t> sB = ecdhB.derive_key(32,keyA.public_value()).bits_of();
790
791     if(sA != sB)
792        return 1;
793
794     std::cout << "agreed key: " << std::endl << Botan::hex_encode(sA);
795     return 0;
796     }
797
798
799.. _mceliece:
800
801McEliece
802--------------------------
803
804McEliece is a cryptographic scheme based on error correcting codes which is
805thought to be resistant to quantum computers. First proposed in 1978, it is fast
806and patent-free. Variants have been proposed and broken, but with suitable
807parameters the original scheme remains secure. However the public keys are quite
808large, which has hindered deployment in the past.
809
810The implementation of McEliece in Botan was contributed by cryptosource GmbH. It
811is based on the implementation HyMES, with the kind permission of Nicolas
812Sendrier and INRIA to release a C++ adaption of their original C code under the
813Botan license. It was then modified by Falko Strenzke to add side channel and
814fault attack countermeasures. You can read more about the implementation at
815http://www.cryptosource.de/docs/mceliece_in_botan.pdf
816
817Encryption in the McEliece scheme consists of choosing a message block of size
818`n`, encoding it in the error correcting code which is the public key, then
819adding `t` bit errors. The code is created such that knowing only the public
820key, decoding `t` errors is intractable, but with the additional knowledge of
821the secret structure of the code a fast decoding technique exists.
822
823The McEliece implementation in HyMES, and also in Botan, uses an optimization to
824reduce the public key size, by converting the public key into a systemic code.
825This means a portion of the public key is a identity matrix, and can be excluded
826from the published public key. However it also means that in McEliece the
827plaintext is represented directly in the ciphertext, with only a small number of
828bit errors. Thus it is absolutely essential to only use McEliece with a CCA2
829secure scheme.
830
831One such scheme, KEM, is provided in Botan currently. It it a somewhat unusual
832scheme in that it outputs two values, a symmetric key for use with an AEAD, and
833an encrypted key. It does this by choosing a random plaintext (n - log2(n)*t
834bits) using ``McEliece_PublicKey::random_plaintext_element``. Then a random
835error mask is chosen and the message is coded and masked. The symmetric key is
836SHA-512(plaintext || error_mask). As long as the resulting key is used with a
837secure AEAD scheme (which can be used for transporting arbitrary amounts of
838data), CCA2 security is provided.
839
840In ``mcies.h`` there are functions for this combination:
841
842.. cpp:function:: secure_vector<uint8_t> mceies_encrypt(const McEliece_PublicKey& pubkey, \
843                  const secure_vector<uint8_t>& pt, \
844                  uint8_t ad[], size_t ad_len, \
845                  RandomNumberGenerator& rng, \
846                  const std::string& aead = "AES-256/OCB")
847
848.. cpp:function:: secure_vector<uint8_t> mceies_decrypt(const McEliece_PrivateKey& privkey, \
849                                                     const secure_vector<uint8_t>& ct, \
850                                                     uint8_t ad[], size_t ad_len, \
851                                                     const std::string& aead = "AES-256/OCB")
852
853For a given security level (SL) a McEliece key would use
854parameters n and t, and have the corresponding key sizes listed:
855
856+-----+------+-----+---------------+----------------+
857| SL  |   n  |   t | public key KB | private key KB |
858+=====+======+=====+===============+================+
859|  80 | 1632 |  33 |            59 |            140 |
860+-----+------+-----+---------------+----------------+
861| 107 | 2280 |  45 |           128 |            300 |
862+-----+------+-----+---------------+----------------+
863| 128 | 2960 |  57 |           195 |            459 |
864+-----+------+-----+---------------+----------------+
865| 147 | 3408 |  67 |           265 |            622 |
866+-----+------+-----+---------------+----------------+
867| 191 | 4624 |  95 |           516 |           1234 |
868+-----+------+-----+---------------+----------------+
869| 256 | 6624 | 115 |           942 |           2184 |
870+-----+------+-----+---------------+----------------+
871
872You can check the speed of McEliece with the suggested parameters above
873using ``botan speed McEliece``
874
875
876eXtended Merkle Signature Scheme (XMSS)
877----------------------------------------
878
879Botan implements the single tree version of the eXtended Merkle Signature
880Scheme (XMSS) using Winternitz One Time Signatures+ (WOTS+). The implementation
881is based on `RFC 8391 "XMSS: eXtended Merkle Signature Scheme"
882<https://tools.ietf.org/html/rfc8391>`_.
883
884XMSS uses the Botan interfaces for public key cryptography.
885The following algorithms are implemented:
886
8871. XMSS-SHA2_10_256
888# XMSS-SHA2_16_256
889# XMSS-SHA2_20_256
890# XMSS-SHA2_10_512
891# XMSS-SHA2_16_512
892# XMSS-SHA2_20_512
893# XMSS-SHAKE_10_256
894# XMSS-SHAKE_16_256
895# XMSS-SHAKE_20_256
896# XMSS-SHAKE_10_512
897# XMSS-SHAKE_16_512
898# XMSS-SHAKE_20_512
899
900The algorithm name contains the hash function name, tree height and digest
901width defined by the corresponding parameter set. Choosing `XMSS-SHA2_10_256`
902for instance will use the SHA2-256 hash function to generate a tree of height
903ten.
904
905Code Example
906^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
907
908The following code snippet shows a minimum example on how to create an XMSS
909public/private key pair and how to use these keys to create and verify a
910signature:
911
912.. code-block:: cpp
913
914    #include <iostream>
915    #include <botan/secmem.h>
916    #include <botan/auto_rng.h>
917    #include <botan/xmss.h>
918
919    int main()
920       {
921       // Create a random number generator used for key generation.
922       Botan::AutoSeeded_RNG rng;
923
924       // create a new public/private key pair using SHA2 256 as hash
925       // function and a tree height of 10.
926       Botan::XMSS_PrivateKey private_key(
927          Botan::XMSS_Parameters::xmss_algorithm_t::XMSS_SHA2_10_256,
928          rng);
929       Botan::XMSS_PublicKey public_key(private_key);
930
931       // create signature operation using the private key.
932       std::unique_ptr<Botan::PK_Ops::Signature> sig_op =
933          private_key.create_signature_op(rng, "", "");
934
935       // create and sign a message using the signature operation.
936       Botan::secure_vector<uint8_t> msg { 0x01, 0x02, 0x03, 0x04 };
937       sig_op->update(msg.data(), msg.size());
938       Botan::secure_vector<uint8_t> sig = sig_op->sign(rng);
939
940       // create verification operation using the public key
941       std::unique_ptr<Botan::PK_Ops::Verification> ver_op =
942          public_key.create_verification_op("", "");
943
944       // verify the signature for the previously generated message.
945       ver_op->update(msg.data(), msg.size());
946       if(ver_op->is_valid_signature(sig.data(), sig.size()))
947          {
948          std::cout << "Success." << std::endl;
949          }
950       else
951          {
952          std::cout << "Error." << std::endl;
953          }
954       }
955