Crypto++  8.2
Free C++ class library of cryptographic schemes
pubkey.h
Go to the documentation of this file.
1 // pubkey.h - originally written and placed in the public domain by Wei Dai
2 
3 /// \file pubkey.h
4 /// \brief This file contains helper classes/functions for implementing public key algorithms.
5 /// \details The class hierachies in this header file tend to look like this:
6 ///
7 /// <pre>
8 /// x1
9 /// +--+
10 /// | |
11 /// y1 z1
12 /// | |
13 /// x2<y1> x2<z1>
14 /// | |
15 /// y2 z2
16 /// | |
17 /// x3<y2> x3<z2>
18 /// | |
19 /// y3 z3
20 /// </pre>
21 ///
22 /// <ul>
23 /// <li>x1, y1, z1 are abstract interface classes defined in cryptlib.h
24 /// <li>x2, y2, z2 are implementations of the interfaces using "abstract policies", which
25 /// are pure virtual functions that should return interfaces to interchangeable algorithms.
26 /// These classes have Base suffixes.
27 /// <li>x3, y3, z3 hold actual algorithms and implement those virtual functions.
28 /// These classes have Impl suffixes.
29 /// </ul>
30 ///
31 /// \details The TF_ prefix means an implementation using trapdoor functions on integers.
32 /// \details The DL_ prefix means an implementation using group operations in groups where discrete log is hard.
33 
34 #ifndef CRYPTOPP_PUBKEY_H
35 #define CRYPTOPP_PUBKEY_H
36 
37 #include "config.h"
38 
39 #if CRYPTOPP_MSC_VERSION
40 # pragma warning(push)
41 # pragma warning(disable: 4702)
42 #endif
43 
44 #include "cryptlib.h"
45 #include "integer.h"
46 #include "algebra.h"
47 #include "modarith.h"
48 #include "filters.h"
49 #include "eprecomp.h"
50 #include "fips140.h"
51 #include "argnames.h"
52 #include "smartptr.h"
53 #include "stdcpp.h"
54 
55 #if defined(__SUNPRO_CC)
56 # define MAYBE_RETURN(x) return x
57 #else
58 # define MAYBE_RETURN(x) CRYPTOPP_UNUSED(x)
59 #endif
60 
61 NAMESPACE_BEGIN(CryptoPP)
62 
63 /// \brief Provides range for plaintext and ciphertext lengths
64 /// \details A trapdoor function is a function that is easy to compute in one direction,
65 /// but difficult to compute in the opposite direction without special knowledge.
66 /// The special knowledge is usually the private key.
67 /// \details Trapdoor functions only handle messages of a limited length or size.
68 /// MaxPreimage is the plaintext's maximum length, and MaxImage is the
69 /// ciphertext's maximum length.
70 /// \sa TrapdoorFunctionBounds(), RandomizedTrapdoorFunction(), TrapdoorFunction(),
71 /// RandomizedTrapdoorFunctionInverse() and TrapdoorFunctionInverse()
72 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE TrapdoorFunctionBounds
73 {
74 public:
75  virtual ~TrapdoorFunctionBounds() {}
76 
77  /// \brief Returns the maximum size of a message before the trapdoor function is applied
78  /// \returns the maximum size of a message before the trapdoor function is applied
79  /// \details Derived classes must implement PreimageBound().
80  virtual Integer PreimageBound() const =0;
81  /// \brief Returns the maximum size of a message after the trapdoor function is applied
82  /// \returns the maximum size of a message after the trapdoor function is applied
83  /// \details Derived classes must implement ImageBound().
84  virtual Integer ImageBound() const =0;
85  /// \brief Returns the maximum size of a message before the trapdoor function is applied bound to a public key
86  /// \returns the maximum size of a message before the trapdoor function is applied bound to a public key
87  /// \details The default implementation returns <tt>PreimageBound() - 1</tt>.
88  virtual Integer MaxPreimage() const {return --PreimageBound();}
89  /// \brief Returns the maximum size of a message after the trapdoor function is applied bound to a public key
90  /// \returns the the maximum size of a message after the trapdoor function is applied bound to a public key
91  /// \details The default implementation returns <tt>ImageBound() - 1</tt>.
92  virtual Integer MaxImage() const {return --ImageBound();}
93 };
94 
95 /// \brief Applies the trapdoor function, using random data if required
96 /// \details ApplyFunction() is the foundation for encrypting a message under a public key.
97 /// Derived classes will override it at some point.
98 /// \sa TrapdoorFunctionBounds(), RandomizedTrapdoorFunction(), TrapdoorFunction(),
99 /// RandomizedTrapdoorFunctionInverse() and TrapdoorFunctionInverse()
100 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE RandomizedTrapdoorFunction : public TrapdoorFunctionBounds
101 {
102 public:
103  virtual ~RandomizedTrapdoorFunction() {}
104 
105  /// \brief Applies the trapdoor function, using random data if required
106  /// \param rng a RandomNumberGenerator derived class
107  /// \param x the message on which the encryption function is applied
108  /// \returns the message x encrypted under the public key
109  /// \details ApplyRandomizedFunction is a generalization of encryption under a public key
110  /// cryptosystem. The RandomNumberGenerator may (or may not) be required.
111  /// Derived classes must implement it.
112  virtual Integer ApplyRandomizedFunction(RandomNumberGenerator &rng, const Integer &x) const =0;
113 
114  /// \brief Determines if the encryption algorithm is randomized
115  /// \returns true if the encryption algorithm is randomized, false otherwise
116  /// \details If IsRandomized() returns false, then NullRNG() can be used.
117  virtual bool IsRandomized() const {return true;}
118 };
119 
120 /// \brief Applies the trapdoor function
121 /// \details ApplyFunction() is the foundation for encrypting a message under a public key.
122 /// Derived classes will override it at some point.
123 /// \sa TrapdoorFunctionBounds(), RandomizedTrapdoorFunction(), TrapdoorFunction(),
124 /// RandomizedTrapdoorFunctionInverse() and TrapdoorFunctionInverse()
125 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE TrapdoorFunction : public RandomizedTrapdoorFunction
126 {
127 public:
128  virtual ~TrapdoorFunction() {}
129 
130  /// \brief Applies the trapdoor function
131  /// \param rng a RandomNumberGenerator derived class
132  /// \param x the message on which the encryption function is applied
133  /// \details ApplyRandomizedFunction is a generalization of encryption under a public key
134  /// cryptosystem. The RandomNumberGenerator may (or may not) be required.
135  /// \details Internally, ApplyRandomizedFunction() calls ApplyFunction() \a
136  /// without the RandomNumberGenerator.
138  {CRYPTOPP_UNUSED(rng); return ApplyFunction(x);}
139  bool IsRandomized() const {return false;}
140 
141  /// \brief Applies the trapdoor
142  /// \param x the message on which the encryption function is applied
143  /// \returns the message x encrypted under the public key
144  /// \details ApplyFunction is a generalization of encryption under a public key
145  /// cryptosystem. Derived classes must implement it.
146  virtual Integer ApplyFunction(const Integer &x) const =0;
147 };
148 
149 /// \brief Applies the inverse of the trapdoor function, using random data if required
150 /// \details CalculateInverse() is the foundation for decrypting a message under a private key
151 /// in a public key cryptosystem. Derived classes will override it at some point.
152 /// \sa TrapdoorFunctionBounds(), RandomizedTrapdoorFunction(), TrapdoorFunction(),
153 /// RandomizedTrapdoorFunctionInverse() and TrapdoorFunctionInverse()
154 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE RandomizedTrapdoorFunctionInverse
155 {
156 public:
158 
159  /// \brief Applies the inverse of the trapdoor function, using random data if required
160  /// \param rng a RandomNumberGenerator derived class
161  /// \param x the message on which the decryption function is applied
162  /// \returns the message x decrypted under the private key
163  /// \details CalculateRandomizedInverse is a generalization of decryption using the private key
164  /// The RandomNumberGenerator may (or may not) be required. Derived classes must implement it.
165  virtual Integer CalculateRandomizedInverse(RandomNumberGenerator &rng, const Integer &x) const =0;
166 
167  /// \brief Determines if the decryption algorithm is randomized
168  /// \returns true if the decryption algorithm is randomized, false otherwise
169  /// \details If IsRandomized() returns false, then NullRNG() can be used.
170  virtual bool IsRandomized() const {return true;}
171 };
172 
173 /// \brief Applies the inverse of the trapdoor function
174 /// \details CalculateInverse() is the foundation for decrypting a message under a private key
175 /// in a public key cryptosystem. Derived classes will override it at some point.
176 /// \sa TrapdoorFunctionBounds(), RandomizedTrapdoorFunction(), TrapdoorFunction(),
177 /// RandomizedTrapdoorFunctionInverse() and TrapdoorFunctionInverse()
178 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE TrapdoorFunctionInverse : public RandomizedTrapdoorFunctionInverse
179 {
180 public:
181  virtual ~TrapdoorFunctionInverse() {}
182 
183  /// \brief Applies the inverse of the trapdoor function
184  /// \param rng a RandomNumberGenerator derived class
185  /// \param x the message on which the decryption function is applied
186  /// \returns the message x decrypted under the private key
187  /// \details CalculateRandomizedInverse is a generalization of decryption using the private key
188  /// \details Internally, CalculateRandomizedInverse() calls CalculateInverse() \a
189  /// without the RandomNumberGenerator.
191  {return CalculateInverse(rng, x);}
192 
193  /// \brief Determines if the decryption algorithm is randomized
194  /// \returns true if the decryption algorithm is randomized, false otherwise
195  /// \details If IsRandomized() returns false, then NullRNG() can be used.
196  bool IsRandomized() const {return false;}
197 
198  /// \brief Calculates the inverse of an element
199  /// \param rng a RandomNumberGenerator derived class
200  /// \param x the element
201  /// \returns the inverse of the element in the group
202  virtual Integer CalculateInverse(RandomNumberGenerator &rng, const Integer &x) const =0;
203 };
204 
205 // ********************************************************
206 
207 /// \brief Message encoding method for public key encryption
208 class CRYPTOPP_NO_VTABLE PK_EncryptionMessageEncodingMethod
209 {
210 public:
212 
213  virtual bool ParameterSupported(const char *name) const
214  {CRYPTOPP_UNUSED(name); return false;}
215 
216  /// max size of unpadded message in bytes, given max size of padded message in bits (1 less than size of modulus)
217  virtual size_t MaxUnpaddedLength(size_t paddedLength) const =0;
218 
219  virtual void Pad(RandomNumberGenerator &rng, const byte *raw, size_t inputLength, byte *padded, size_t paddedBitLength, const NameValuePairs &parameters) const =0;
220 
221  virtual DecodingResult Unpad(const byte *padded, size_t paddedBitLength, byte *raw, const NameValuePairs &parameters) const =0;
222 };
223 
224 // ********************************************************
225 
226 /// \brief The base for trapdoor based cryptosystems
227 /// \tparam TFI trapdoor function interface derived class
228 /// \tparam MEI message encoding interface derived class
229 template <class TFI, class MEI>
230 class CRYPTOPP_NO_VTABLE TF_Base
231 {
232 protected:
233  virtual ~TF_Base() {}
234 
235  virtual const TrapdoorFunctionBounds & GetTrapdoorFunctionBounds() const =0;
236 
237  typedef TFI TrapdoorFunctionInterface;
238  virtual const TrapdoorFunctionInterface & GetTrapdoorFunctionInterface() const =0;
239 
240  typedef MEI MessageEncodingInterface;
241  virtual const MessageEncodingInterface & GetMessageEncodingInterface() const =0;
242 };
243 
244 // ********************************************************
245 
246 /// \brief Public key trapdoor function default implementation
247 /// \tparam BASE public key cryptosystem with a fixed length
248 template <class BASE>
249 class CRYPTOPP_NO_VTABLE PK_FixedLengthCryptoSystemImpl : public BASE
250 {
251 public:
252  virtual ~PK_FixedLengthCryptoSystemImpl() {}
253 
254  size_t MaxPlaintextLength(size_t ciphertextLength) const
255  {return ciphertextLength == FixedCiphertextLength() ? FixedMaxPlaintextLength() : 0;}
256  size_t CiphertextLength(size_t plaintextLength) const
257  {return plaintextLength <= FixedMaxPlaintextLength() ? FixedCiphertextLength() : 0;}
258 
259  virtual size_t FixedMaxPlaintextLength() const =0;
260  virtual size_t FixedCiphertextLength() const =0;
261 };
262 
263 /// \brief Trapdoor function cryptosystem base class
264 /// \tparam INTFACE public key cryptosystem base interface
265 /// \tparam BASE public key cryptosystem implementation base
266 template <class INTFACE, class BASE>
267 class CRYPTOPP_NO_VTABLE TF_CryptoSystemBase : public PK_FixedLengthCryptoSystemImpl<INTFACE>, protected BASE
268 {
269 public:
270  virtual ~TF_CryptoSystemBase() {}
271 
272  bool ParameterSupported(const char *name) const {return this->GetMessageEncodingInterface().ParameterSupported(name);}
273  size_t FixedMaxPlaintextLength() const {return this->GetMessageEncodingInterface().MaxUnpaddedLength(PaddedBlockBitLength());}
274  size_t FixedCiphertextLength() const {return this->GetTrapdoorFunctionBounds().MaxImage().ByteCount();}
275 
276 protected:
277  size_t PaddedBlockByteLength() const {return BitsToBytes(PaddedBlockBitLength());}
278  // Coverity finding on potential overflow/underflow.
279  size_t PaddedBlockBitLength() const {return SaturatingSubtract(this->GetTrapdoorFunctionBounds().PreimageBound().BitCount(),1U);}
280 };
281 
282 /// \brief Trapdoor function cryptosystems decryption base class
283 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE TF_DecryptorBase : public TF_CryptoSystemBase<PK_Decryptor, TF_Base<TrapdoorFunctionInverse, PK_EncryptionMessageEncodingMethod> >
284 {
285 public:
286  virtual ~TF_DecryptorBase() {}
287 
288  DecodingResult Decrypt(RandomNumberGenerator &rng, const byte *ciphertext, size_t ciphertextLength, byte *plaintext, const NameValuePairs &parameters = g_nullNameValuePairs) const;
289 };
290 
291 /// \brief Trapdoor function cryptosystems encryption base class
292 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE TF_EncryptorBase : public TF_CryptoSystemBase<PK_Encryptor, TF_Base<RandomizedTrapdoorFunction, PK_EncryptionMessageEncodingMethod> >
293 {
294 public:
295  virtual ~TF_EncryptorBase() {}
296 
297  void Encrypt(RandomNumberGenerator &rng, const byte *plaintext, size_t plaintextLength, byte *ciphertext, const NameValuePairs &parameters = g_nullNameValuePairs) const;
298 };
299 
300 // ********************************************************
301 
302 // Typedef change due to Clang, http://github.com/weidai11/cryptopp/issues/300
303 typedef std::pair<const byte *, unsigned int> HashIdentifier;
304 
305 /// \brief Interface for message encoding method for public key signature schemes.
306 /// \details PK_SignatureMessageEncodingMethod provides interfaces for message
307 /// encoding method for public key signature schemes. The methods support both
308 /// trapdoor functions (<tt>TF_*</tt>) and discrete logarithm (<tt>DL_*</tt>)
309 /// based schemes.
310 class CRYPTOPP_NO_VTABLE PK_SignatureMessageEncodingMethod
311 {
312 public:
314 
315  virtual size_t MinRepresentativeBitLength(size_t hashIdentifierLength, size_t digestLength) const
316  {CRYPTOPP_UNUSED(hashIdentifierLength); CRYPTOPP_UNUSED(digestLength); return 0;}
317  virtual size_t MaxRecoverableLength(size_t representativeBitLength, size_t hashIdentifierLength, size_t digestLength) const
318  {CRYPTOPP_UNUSED(representativeBitLength); CRYPTOPP_UNUSED(representativeBitLength); CRYPTOPP_UNUSED(hashIdentifierLength); CRYPTOPP_UNUSED(digestLength); return 0;}
319 
320  /// \brief Determines whether an encoding method requires a random number generator
321  /// \return true if the encoding method requires a RandomNumberGenerator()
322  /// \details if IsProbabilistic() returns false, then NullRNG() can be passed to functions that take
323  /// RandomNumberGenerator().
324  /// \sa Bellare and Rogaway<a href="http://grouper.ieee.org/groups/1363/P1363a/contributions/pss-submission.pdf">PSS:
325  /// Provably Secure Encoding Method for Digital Signatures</a>
326  bool IsProbabilistic() const
327  {return true;}
328  bool AllowNonrecoverablePart() const
329  {throw NotImplemented("PK_MessageEncodingMethod: this signature scheme does not support message recovery");}
330  virtual bool RecoverablePartFirst() const
331  {throw NotImplemented("PK_MessageEncodingMethod: this signature scheme does not support message recovery");}
332 
333  // for verification, DL
334  virtual void ProcessSemisignature(HashTransformation &hash, const byte *semisignature, size_t semisignatureLength) const
335  {CRYPTOPP_UNUSED(hash); CRYPTOPP_UNUSED(semisignature); CRYPTOPP_UNUSED(semisignatureLength);}
336 
337  // for signature
338  virtual void ProcessRecoverableMessage(HashTransformation &hash,
339  const byte *recoverableMessage, size_t recoverableMessageLength,
340  const byte *presignature, size_t presignatureLength,
341  SecByteBlock &semisignature) const
342  {
343  CRYPTOPP_UNUSED(hash);CRYPTOPP_UNUSED(recoverableMessage); CRYPTOPP_UNUSED(recoverableMessageLength);
344  CRYPTOPP_UNUSED(presignature); CRYPTOPP_UNUSED(presignatureLength); CRYPTOPP_UNUSED(semisignature);
345  if (RecoverablePartFirst())
346  CRYPTOPP_ASSERT(!"ProcessRecoverableMessage() not implemented");
347  }
348 
349  virtual void ComputeMessageRepresentative(RandomNumberGenerator &rng,
350  const byte *recoverableMessage, size_t recoverableMessageLength,
351  HashTransformation &hash, HashIdentifier hashIdentifier, bool messageEmpty,
352  byte *representative, size_t representativeBitLength) const =0;
353 
354  virtual bool VerifyMessageRepresentative(
355  HashTransformation &hash, HashIdentifier hashIdentifier, bool messageEmpty,
356  byte *representative, size_t representativeBitLength) const =0;
357 
358  virtual DecodingResult RecoverMessageFromRepresentative( // for TF
359  HashTransformation &hash, HashIdentifier hashIdentifier, bool messageEmpty,
360  byte *representative, size_t representativeBitLength,
361  byte *recoveredMessage) const
362  {CRYPTOPP_UNUSED(hash);CRYPTOPP_UNUSED(hashIdentifier); CRYPTOPP_UNUSED(messageEmpty);
363  CRYPTOPP_UNUSED(representative); CRYPTOPP_UNUSED(representativeBitLength); CRYPTOPP_UNUSED(recoveredMessage);
364  throw NotImplemented("PK_MessageEncodingMethod: this signature scheme does not support message recovery");}
365 
366  virtual DecodingResult RecoverMessageFromSemisignature( // for DL
367  HashTransformation &hash, HashIdentifier hashIdentifier,
368  const byte *presignature, size_t presignatureLength,
369  const byte *semisignature, size_t semisignatureLength,
370  byte *recoveredMessage) const
371  {CRYPTOPP_UNUSED(hash);CRYPTOPP_UNUSED(hashIdentifier); CRYPTOPP_UNUSED(presignature); CRYPTOPP_UNUSED(presignatureLength);
372  CRYPTOPP_UNUSED(semisignature); CRYPTOPP_UNUSED(semisignatureLength); CRYPTOPP_UNUSED(recoveredMessage);
373  throw NotImplemented("PK_MessageEncodingMethod: this signature scheme does not support message recovery");}
374 
375  // VC60 workaround
377  {
378  template <class H> struct HashIdentifierLookup2
379  {
380  static HashIdentifier CRYPTOPP_API Lookup()
381  {
382  return HashIdentifier(static_cast<const byte *>(NULLPTR), 0);
383  }
384  };
385  };
386 };
387 
388 /// \brief Interface for message encoding method for public key signature schemes.
389 /// \details PK_DeterministicSignatureMessageEncodingMethod provides interfaces
390 /// for message encoding method for public key signature schemes.
392 {
393 public:
394  bool VerifyMessageRepresentative(
395  HashTransformation &hash, HashIdentifier hashIdentifier, bool messageEmpty,
396  byte *representative, size_t representativeBitLength) const;
397 };
398 
399 /// \brief Interface for message encoding method for public key signature schemes.
400 /// \details PK_RecoverableSignatureMessageEncodingMethod provides interfaces
401 /// for message encoding method for public key signature schemes.
403 {
404 public:
405  bool VerifyMessageRepresentative(
406  HashTransformation &hash, HashIdentifier hashIdentifier, bool messageEmpty,
407  byte *representative, size_t representativeBitLength) const;
408 };
409 
410 /// \brief Interface for message encoding method for public key signature schemes.
411 /// \details DL_SignatureMessageEncodingMethod_DSA provides interfaces
412 /// for message encoding method for DSA.
414 {
415 public:
416  void ComputeMessageRepresentative(RandomNumberGenerator &rng,
417  const byte *recoverableMessage, size_t recoverableMessageLength,
418  HashTransformation &hash, HashIdentifier hashIdentifier, bool messageEmpty,
419  byte *representative, size_t representativeBitLength) const;
420 };
421 
422 /// \brief Interface for message encoding method for public key signature schemes.
423 /// \details DL_SignatureMessageEncodingMethod_NR provides interfaces
424 /// for message encoding method for Nyberg-Rueppel.
426 {
427 public:
428  void ComputeMessageRepresentative(RandomNumberGenerator &rng,
429  const byte *recoverableMessage, size_t recoverableMessageLength,
430  HashTransformation &hash, HashIdentifier hashIdentifier, bool messageEmpty,
431  byte *representative, size_t representativeBitLength) const;
432 };
433 
434 #if 0
435 /// \brief Interface for message encoding method for public key signature schemes.
436 /// \details DL_SignatureMessageEncodingMethod_SM2 provides interfaces
437 /// for message encoding method for SM2.
438 class CRYPTOPP_DLL DL_SignatureMessageEncodingMethod_SM2 : public PK_DeterministicSignatureMessageEncodingMethod
439 {
440 public:
441  void ComputeMessageRepresentative(RandomNumberGenerator &rng,
442  const byte *recoverableMessage, size_t recoverableMessageLength,
443  HashTransformation &hash, HashIdentifier hashIdentifier, bool messageEmpty,
444  byte *representative, size_t representativeBitLength) const;
445 };
446 #endif
447 
448 /// \brief Interface for message encoding method for public key signature schemes.
449 /// \details PK_MessageAccumulatorBase provides interfaces
450 /// for message encoding method.
451 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_MessageAccumulatorBase : public PK_MessageAccumulator
452 {
453 public:
454  PK_MessageAccumulatorBase() : m_empty(true) {}
455 
456  virtual HashTransformation & AccessHash() =0;
457 
458  void Update(const byte *input, size_t length)
459  {
460  AccessHash().Update(input, length);
461  m_empty = m_empty && length == 0;
462  }
463 
464  SecByteBlock m_recoverableMessage, m_representative, m_presignature, m_semisignature;
465  Integer m_k, m_s;
466  bool m_empty;
467 };
468 
469 /// \brief Interface for message encoding method for public key signature schemes.
470 /// \details PK_MessageAccumulatorBase provides interfaces
471 /// for message encoding method.
472 template <class HASH_ALGORITHM>
473 class PK_MessageAccumulatorImpl : public PK_MessageAccumulatorBase, protected ObjectHolder<HASH_ALGORITHM>
474 {
475 public:
476  HashTransformation & AccessHash() {return this->m_object;}
477 };
478 
479 /// \brief Trapdoor Function (TF) Signature Scheme base class
480 /// \tparam INTFACE interface
481 /// \tparam BASE base class
482 template <class INTFACE, class BASE>
483 class CRYPTOPP_NO_VTABLE TF_SignatureSchemeBase : public INTFACE, protected BASE
484 {
485 public:
486  virtual ~TF_SignatureSchemeBase() {}
487 
488  size_t SignatureLength() const
489  {return this->GetTrapdoorFunctionBounds().MaxPreimage().ByteCount();}
490  size_t MaxRecoverableLength() const
491  {return this->GetMessageEncodingInterface().MaxRecoverableLength(MessageRepresentativeBitLength(), GetHashIdentifier().second, GetDigestSize());}
492  size_t MaxRecoverableLengthFromSignatureLength(size_t signatureLength) const
493  {CRYPTOPP_UNUSED(signatureLength); return this->MaxRecoverableLength();}
494 
495  bool IsProbabilistic() const
496  {return this->GetTrapdoorFunctionInterface().IsRandomized() || this->GetMessageEncodingInterface().IsProbabilistic();}
497  bool AllowNonrecoverablePart() const
498  {return this->GetMessageEncodingInterface().AllowNonrecoverablePart();}
499  bool RecoverablePartFirst() const
500  {return this->GetMessageEncodingInterface().RecoverablePartFirst();}
501 
502 protected:
503  size_t MessageRepresentativeLength() const {return BitsToBytes(MessageRepresentativeBitLength());}
504  // Coverity finding on potential overflow/underflow.
505  size_t MessageRepresentativeBitLength() const {return SaturatingSubtract(this->GetTrapdoorFunctionBounds().ImageBound().BitCount(),1U);}
506  virtual HashIdentifier GetHashIdentifier() const =0;
507  virtual size_t GetDigestSize() const =0;
508 };
509 
510 /// \brief Trapdoor Function (TF) Signer base class
511 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE TF_SignerBase : public TF_SignatureSchemeBase<PK_Signer, TF_Base<RandomizedTrapdoorFunctionInverse, PK_SignatureMessageEncodingMethod> >
512 {
513 public:
514  virtual ~TF_SignerBase() {}
515 
516  void InputRecoverableMessage(PK_MessageAccumulator &messageAccumulator, const byte *recoverableMessage, size_t recoverableMessageLength) const;
517  size_t SignAndRestart(RandomNumberGenerator &rng, PK_MessageAccumulator &messageAccumulator, byte *signature, bool restart=true) const;
518 };
519 
520 /// \brief Trapdoor Function (TF) Verifier base class
521 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE TF_VerifierBase : public TF_SignatureSchemeBase<PK_Verifier, TF_Base<TrapdoorFunction, PK_SignatureMessageEncodingMethod> >
522 {
523 public:
524  virtual ~TF_VerifierBase() {}
525 
526  void InputSignature(PK_MessageAccumulator &messageAccumulator, const byte *signature, size_t signatureLength) const;
527  bool VerifyAndRestart(PK_MessageAccumulator &messageAccumulator) const;
528  DecodingResult RecoverAndRestart(byte *recoveredMessage, PK_MessageAccumulator &recoveryAccumulator) const;
529 };
530 
531 // ********************************************************
532 
533 /// \brief Trapdoor Function (TF) scheme options
534 /// \tparam T1 algorithm info class
535 /// \tparam T2 keys class with public and private key
536 /// \tparam T3 message encoding class
537 template <class T1, class T2, class T3>
539 {
540  typedef T1 AlgorithmInfo;
541  typedef T2 Keys;
542  typedef typename Keys::PrivateKey PrivateKey;
543  typedef typename Keys::PublicKey PublicKey;
544  typedef T3 MessageEncodingMethod;
545 };
546 
547 /// \brief Trapdoor Function (TF) signature scheme options
548 /// \tparam T1 algorithm info class
549 /// \tparam T2 keys class with public and private key
550 /// \tparam T3 message encoding class
551 /// \tparam T4 HashTransformation class
552 template <class T1, class T2, class T3, class T4>
554 {
555  typedef T4 HashFunction;
556 };
557 
558 /// \brief Trapdoor Function (TF) base implementation
559 /// \tparam BASE base class
560 /// \tparam SCHEME_OPTIONS scheme options class
561 /// \tparam KEY_CLASS key class
562 template <class BASE, class SCHEME_OPTIONS, class KEY_CLASS>
563 class CRYPTOPP_NO_VTABLE TF_ObjectImplBase : public AlgorithmImpl<BASE, typename SCHEME_OPTIONS::AlgorithmInfo>
564 {
565 public:
566  typedef SCHEME_OPTIONS SchemeOptions;
567  typedef KEY_CLASS KeyClass;
568 
569  virtual ~TF_ObjectImplBase() {}
570 
571  PublicKey & AccessPublicKey() {return AccessKey();}
572  const PublicKey & GetPublicKey() const {return GetKey();}
573 
574  PrivateKey & AccessPrivateKey() {return AccessKey();}
575  const PrivateKey & GetPrivateKey() const {return GetKey();}
576 
577  virtual const KeyClass & GetKey() const =0;
578  virtual KeyClass & AccessKey() =0;
579 
580  const KeyClass & GetTrapdoorFunction() const {return GetKey();}
581 
582  PK_MessageAccumulator * NewSignatureAccumulator(RandomNumberGenerator &rng) const
583  {
584  CRYPTOPP_UNUSED(rng);
586  }
587  PK_MessageAccumulator * NewVerificationAccumulator() const
588  {
590  }
591 
592 protected:
593  const typename BASE::MessageEncodingInterface & GetMessageEncodingInterface() const
595  const TrapdoorFunctionBounds & GetTrapdoorFunctionBounds() const
596  {return GetKey();}
597  const typename BASE::TrapdoorFunctionInterface & GetTrapdoorFunctionInterface() const
598  {return GetKey();}
599 
600  // for signature scheme
601  HashIdentifier GetHashIdentifier() const
602  {
603  typedef typename SchemeOptions::MessageEncodingMethod::HashIdentifierLookup::template HashIdentifierLookup2<typename SchemeOptions::HashFunction> L;
604  return L::Lookup();
605  }
606  size_t GetDigestSize() const
607  {
608  typedef typename SchemeOptions::HashFunction H;
609  return H::DIGESTSIZE;
610  }
611 };
612 
613 /// \brief Trapdoor Function (TF) signature with external reference
614 /// \tparam BASE base class
615 /// \tparam SCHEME_OPTIONS scheme options class
616 /// \tparam KEY key class
617 /// \details TF_ObjectImplExtRef() holds a pointer to an external key structure
618 template <class BASE, class SCHEME_OPTIONS, class KEY>
619 class TF_ObjectImplExtRef : public TF_ObjectImplBase<BASE, SCHEME_OPTIONS, KEY>
620 {
621 public:
622  virtual ~TF_ObjectImplExtRef() {}
623 
624  TF_ObjectImplExtRef(const KEY *pKey = NULLPTR) : m_pKey(pKey) {}
625  void SetKeyPtr(const KEY *pKey) {m_pKey = pKey;}
626 
627  const KEY & GetKey() const {return *m_pKey;}
628  KEY & AccessKey() {throw NotImplemented("TF_ObjectImplExtRef: cannot modify refererenced key");}
629 
630 private:
631  const KEY * m_pKey;
632 };
633 
634 /// \brief Trapdoor Function (TF) signature scheme options
635 /// \tparam BASE base class
636 /// \tparam SCHEME_OPTIONS scheme options class
637 /// \tparam KEY_CLASS key class
638 /// \details TF_ObjectImpl() holds a reference to a trapdoor function
639 template <class BASE, class SCHEME_OPTIONS, class KEY_CLASS>
640 class CRYPTOPP_NO_VTABLE TF_ObjectImpl : public TF_ObjectImplBase<BASE, SCHEME_OPTIONS, KEY_CLASS>
641 {
642 public:
643  typedef KEY_CLASS KeyClass;
644 
645  virtual ~TF_ObjectImpl() {}
646 
647  const KeyClass & GetKey() const {return m_trapdoorFunction;}
648  KeyClass & AccessKey() {return m_trapdoorFunction;}
649 
650 private:
651  KeyClass m_trapdoorFunction;
652 };
653 
654 /// \brief Trapdoor Function (TF) decryptor options
655 /// \tparam SCHEME_OPTIONS scheme options class
656 template <class SCHEME_OPTIONS>
657 class TF_DecryptorImpl : public TF_ObjectImpl<TF_DecryptorBase, SCHEME_OPTIONS, typename SCHEME_OPTIONS::PrivateKey>
658 {
659 };
660 
661 /// \brief Trapdoor Function (TF) encryptor options
662 /// \tparam SCHEME_OPTIONS scheme options class
663 template <class SCHEME_OPTIONS>
664 class TF_EncryptorImpl : public TF_ObjectImpl<TF_EncryptorBase, SCHEME_OPTIONS, typename SCHEME_OPTIONS::PublicKey>
665 {
666 };
667 
668 /// \brief Trapdoor Function (TF) encryptor options
669 /// \tparam SCHEME_OPTIONS scheme options class
670 template <class SCHEME_OPTIONS>
671 class TF_SignerImpl : public TF_ObjectImpl<TF_SignerBase, SCHEME_OPTIONS, typename SCHEME_OPTIONS::PrivateKey>
672 {
673 };
674 
675 /// \brief Trapdoor Function (TF) encryptor options
676 /// \tparam SCHEME_OPTIONS scheme options class
677 template <class SCHEME_OPTIONS>
678 class TF_VerifierImpl : public TF_ObjectImpl<TF_VerifierBase, SCHEME_OPTIONS, typename SCHEME_OPTIONS::PublicKey>
679 {
680 };
681 
682 // ********************************************************
683 
684 /// \brief Mask generation function interface
685 class CRYPTOPP_NO_VTABLE MaskGeneratingFunction
686 {
687 public:
688  virtual ~MaskGeneratingFunction() {}
689 
690  /// \brief Generate and apply mask
691  /// \param hash HashTransformation derived class
692  /// \param output the destination byte array
693  /// \param outputLength the size fo the the destination byte array
694  /// \param input the message to hash
695  /// \param inputLength the size of the message
696  /// \param mask flag indicating whether to apply the mask
697  virtual void GenerateAndMask(HashTransformation &hash, byte *output, size_t outputLength, const byte *input, size_t inputLength, bool mask = true) const =0;
698 };
699 
700 /// \fn P1363_MGF1KDF2_Common
701 /// \brief P1363 mask generation function
702 /// \param hash HashTransformation derived class
703 /// \param output the destination byte array
704 /// \param outputLength the size fo the the destination byte array
705 /// \param input the message to hash
706 /// \param inputLength the size of the message
707 /// \param derivationParams additional derivation parameters
708 /// \param derivationParamsLength the size of the additional derivation parameters
709 /// \param mask flag indicating whether to apply the mask
710 /// \param counterStart starting counter value used in generation function
711 CRYPTOPP_DLL void CRYPTOPP_API P1363_MGF1KDF2_Common(HashTransformation &hash, byte *output, size_t outputLength, const byte *input, size_t inputLength, const byte *derivationParams, size_t derivationParamsLength, bool mask, unsigned int counterStart);
712 
713 /// \brief P1363 mask generation function
715 {
716 public:
717  CRYPTOPP_STATIC_CONSTEXPR const char* CRYPTOPP_API StaticAlgorithmName() {return "MGF1";}
718  void GenerateAndMask(HashTransformation &hash, byte *output, size_t outputLength, const byte *input, size_t inputLength, bool mask = true) const
719  {
720  P1363_MGF1KDF2_Common(hash, output, outputLength, input, inputLength, NULLPTR, 0, mask, 0);
721  }
722 };
723 
724 // ********************************************************
725 
726 /// \brief P1363 key derivation function
727 /// \tparam H hash function used in the derivation
728 template <class H>
730 {
731 public:
732  static void CRYPTOPP_API DeriveKey(byte *output, size_t outputLength, const byte *input, size_t inputLength, const byte *derivationParams, size_t derivationParamsLength)
733  {
734  H h;
735  P1363_MGF1KDF2_Common(h, output, outputLength, input, inputLength, derivationParams, derivationParamsLength, false, 1);
736  }
737 };
738 
739 // ********************************************************
740 
741 /// \brief Exception thrown when an invalid group element is encountered
742 /// \details Thrown by DecodeElement and AgreeWithStaticPrivateKey
744 {
745 public:
746  DL_BadElement() : InvalidDataFormat("CryptoPP: invalid group element") {}
747 };
748 
749 /// \brief Interface for Discrete Log (DL) group parameters
750 /// \tparam T element in the group
751 /// \details The element is usually an Integer, \ref ECP "ECP::Point" or \ref EC2N "EC2N::Point"
752 template <class T>
753 class CRYPTOPP_NO_VTABLE DL_GroupParameters : public CryptoParameters
754 {
756 
757 public:
758  typedef T Element;
759 
760  virtual ~DL_GroupParameters() {}
761 
762  DL_GroupParameters() : m_validationLevel(0) {}
763 
764  // CryptoMaterial
765  bool Validate(RandomNumberGenerator &rng, unsigned int level) const
766  {
767  if (!GetBasePrecomputation().IsInitialized())
768  return false;
769 
770  if (m_validationLevel > level)
771  return true;
772 
773  CRYPTOPP_ASSERT(ValidateGroup(rng, level));
774  bool pass = ValidateGroup(rng, level);
775  CRYPTOPP_ASSERT(ValidateElement(level, GetSubgroupGenerator(), &GetBasePrecomputation()));
776  pass = pass && ValidateElement(level, GetSubgroupGenerator(), &GetBasePrecomputation());
777 
778  m_validationLevel = pass ? level+1 : 0;
779 
780  return pass;
781  }
782 
783  bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
784  {
785  return GetValueHelper(this, name, valueType, pValue)
786  CRYPTOPP_GET_FUNCTION_ENTRY(SubgroupOrder)
787  CRYPTOPP_GET_FUNCTION_ENTRY(SubgroupGenerator)
788  ;
789  }
790 
791  /// \brief Determines whether the object supports precomputation
792  /// \return true if the object supports precomputation, false otherwise
793  /// \sa Precompute()
794  bool SupportsPrecomputation() const {return true;}
795 
796  /// \brief Perform precomputation
797  /// \param precomputationStorage the suggested number of objects for the precompute table
798  /// \throws NotImplemented
799  /// \details The exact semantics of Precompute() varies, but it typically means calculate
800  /// a table of n objects that can be used later to speed up computation.
801  /// \details If a derived class does not override Precompute(), then the base class throws
802  /// NotImplemented.
803  /// \sa SupportsPrecomputation(), LoadPrecomputation(), SavePrecomputation()
804  void Precompute(unsigned int precomputationStorage=16)
805  {
806  AccessBasePrecomputation().Precompute(GetGroupPrecomputation(), GetSubgroupOrder().BitCount(), precomputationStorage);
807  }
808 
809  /// \brief Retrieve previously saved precomputation
810  /// \param storedPrecomputation BufferedTransformation with the saved precomputation
811  /// \throws NotImplemented
812  /// \sa SupportsPrecomputation(), Precompute()
813  void LoadPrecomputation(BufferedTransformation &storedPrecomputation)
814  {
815  AccessBasePrecomputation().Load(GetGroupPrecomputation(), storedPrecomputation);
816  m_validationLevel = 0;
817  }
818 
819  /// \brief Save precomputation for later use
820  /// \param storedPrecomputation BufferedTransformation to write the precomputation
821  /// \throws NotImplemented
822  /// \sa SupportsPrecomputation(), Precompute()
823  void SavePrecomputation(BufferedTransformation &storedPrecomputation) const
824  {
825  GetBasePrecomputation().Save(GetGroupPrecomputation(), storedPrecomputation);
826  }
827 
828  /// \brief Retrieves the subgroup generator
829  /// \return the subgroup generator
830  /// \details The subgroup generator is retrieved from the base precomputation
831  virtual const Element & GetSubgroupGenerator() const {return GetBasePrecomputation().GetBase(GetGroupPrecomputation());}
832 
833  /// \brief Sets the subgroup generator
834  /// \param base the new subgroup generator
835  /// \details The subgroup generator is set in the base precomputation
836  virtual void SetSubgroupGenerator(const Element &base) {AccessBasePrecomputation().SetBase(GetGroupPrecomputation(), base);}
837 
838  /// \brief Exponentiates the base
839  /// \return the element after exponentiation
840  /// \details ExponentiateBase() calls GetBasePrecomputation() and then exponentiates.
841  virtual Element ExponentiateBase(const Integer &exponent) const
842  {
843  return GetBasePrecomputation().Exponentiate(GetGroupPrecomputation(), exponent);
844  }
845 
846  /// \brief Exponentiates an element
847  /// \param base the base elemenet
848  /// \param exponent the exponent to raise the base
849  /// \return the result of the exponentiation
850  /// \details Internally, ExponentiateElement() calls SimultaneousExponentiate().
851  virtual Element ExponentiateElement(const Element &base, const Integer &exponent) const
852  {
853  Element result;
854  SimultaneousExponentiate(&result, base, &exponent, 1);
855  return result;
856  }
857 
858  /// \brief Retrieves the group precomputation
859  /// \return a const reference to the group precomputation
860  virtual const DL_GroupPrecomputation<Element> & GetGroupPrecomputation() const =0;
861 
862  /// \brief Retrieves the group precomputation
863  /// \return a const reference to the group precomputation using a fixed base
864  virtual const DL_FixedBasePrecomputation<Element> & GetBasePrecomputation() const =0;
865 
866  /// \brief Retrieves the group precomputation
867  /// \return a non-const reference to the group precomputation using a fixed base
868  virtual DL_FixedBasePrecomputation<Element> & AccessBasePrecomputation() =0;
869 
870  /// \brief Retrieves the subgroup order
871  /// \return the order of subgroup generated by the base element
872  virtual const Integer & GetSubgroupOrder() const =0;
873 
874  /// \brief Retrieves the maximum exponent for the group
875  /// \return the maximum exponent for the group
876  virtual Integer GetMaxExponent() const =0;
877 
878  /// \brief Retrieves the order of the group
879  /// \return the order of the group
880  /// \details Either GetGroupOrder() or GetCofactor() must be overridden in a derived class.
881  virtual Integer GetGroupOrder() const {return GetSubgroupOrder()*GetCofactor();}
882 
883  /// \brief Retrieves the cofactor
884  /// \return the cofactor
885  /// \details Either GetGroupOrder() or GetCofactor() must be overridden in a derived class.
886  virtual Integer GetCofactor() const {return GetGroupOrder()/GetSubgroupOrder();}
887 
888  /// \brief Retrieves the encoded element's size
889  /// \param reversible flag indicating the encoding format
890  /// \return encoded element's size, in bytes
891  /// \details The format of the encoded element varies by the underlying type of the element and the
892  /// reversible flag. GetEncodedElementSize() must be implemented in a derived class.
893  /// \sa GetEncodedElementSize(), EncodeElement(), DecodeElement()
894  virtual unsigned int GetEncodedElementSize(bool reversible) const =0;
895 
896  /// \brief Encodes the element
897  /// \param reversible flag indicating the encoding format
898  /// \param element reference to the element to encode
899  /// \param encoded destination byte array for the encoded element
900  /// \details EncodeElement() must be implemented in a derived class.
901  /// \pre <tt>COUNTOF(encoded) == GetEncodedElementSize()</tt>
902  virtual void EncodeElement(bool reversible, const Element &element, byte *encoded) const =0;
903 
904  /// \brief Decodes the element
905  /// \param encoded byte array with the encoded element
906  /// \param checkForGroupMembership flag indicating if the element should be validated
907  /// \return Element after decoding
908  /// \details DecodeElement() must be implemented in a derived class.
909  /// \pre <tt>COUNTOF(encoded) == GetEncodedElementSize()</tt>
910  virtual Element DecodeElement(const byte *encoded, bool checkForGroupMembership) const =0;
911 
912  /// \brief Converts an element to an Integer
913  /// \param element the element to convert to an Integer
914  /// \return Element after converting to an Integer
915  /// \details ConvertElementToInteger() must be implemented in a derived class.
916  virtual Integer ConvertElementToInteger(const Element &element) const =0;
917 
918  /// \brief Check the group for errors
919  /// \param rng RandomNumberGenerator for objects which use randomized testing
920  /// \param level level of thoroughness
921  /// \return true if the tests succeed, false otherwise
922  /// \details There are four levels of thoroughness:
923  /// <ul>
924  /// <li>0 - using this object won't cause a crash or exception
925  /// <li>1 - this object will probably function, and encrypt, sign, other operations correctly
926  /// <li>2 - ensure this object will function correctly, and perform reasonable security checks
927  /// <li>3 - perform reasonable security checks, and do checks that may take a long time
928  /// </ul>
929  /// \details Level 0 does not require a RandomNumberGenerator. A NullRNG() can be used for level 0.
930  /// Level 1 may not check for weak keys and such. Levels 2 and 3 are recommended.
931  /// \details ValidateGroup() must be implemented in a derived class.
932  virtual bool ValidateGroup(RandomNumberGenerator &rng, unsigned int level) const =0;
933 
934  /// \brief Check the element for errors
935  /// \param level level of thoroughness
936  /// \param element element to check
937  /// \param precomp optional pointer to DL_FixedBasePrecomputation
938  /// \return true if the tests succeed, false otherwise
939  /// \details There are four levels of thoroughness:
940  /// <ul>
941  /// <li>0 - using this object won't cause a crash or exception
942  /// <li>1 - this object will probably function, and encrypt, sign, other operations correctly
943  /// <li>2 - ensure this object will function correctly, and perform reasonable security checks
944  /// <li>3 - perform reasonable security checks, and do checks that may take a long time
945  /// </ul>
946  /// \details Level 0 performs group membership checks. Level 1 may not check for weak keys and such.
947  /// Levels 2 and 3 are recommended.
948  /// \details ValidateElement() must be implemented in a derived class.
949  virtual bool ValidateElement(unsigned int level, const Element &element, const DL_FixedBasePrecomputation<Element> *precomp) const =0;
950 
951  virtual bool FastSubgroupCheckAvailable() const =0;
952 
953  /// \brief Determines if an element is an identity
954  /// \param element element to check
955  /// \return true if the element is an identity, false otherwise
956  /// \details The identity element or or neutral element is a special element in a group that leaves
957  /// other elements unchanged when combined with it.
958  /// \details IsIdentity() must be implemented in a derived class.
959  virtual bool IsIdentity(const Element &element) const =0;
960 
961  /// \brief Exponentiates a base to multiple exponents
962  /// \param results an array of Elements
963  /// \param base the base to raise to the exponents
964  /// \param exponents an array of exponents
965  /// \param exponentsCount the number of exponents in the array
966  /// \details SimultaneousExponentiate() raises the base to each exponent in the exponents array and stores the
967  /// result at the respective position in the results array.
968  /// \details SimultaneousExponentiate() must be implemented in a derived class.
969  /// \pre <tt>COUNTOF(results) == exponentsCount</tt>
970  /// \pre <tt>COUNTOF(exponents) == exponentsCount</tt>
971  virtual void SimultaneousExponentiate(Element *results, const Element &base, const Integer *exponents, unsigned int exponentsCount) const =0;
972 
973 protected:
974  void ParametersChanged() {m_validationLevel = 0;}
975 
976 private:
977  mutable unsigned int m_validationLevel;
978 };
979 
980 /// \brief Base implementation of Discrete Log (DL) group parameters
981 /// \tparam GROUP_PRECOMP group precomputation class
982 /// \tparam BASE_PRECOMP fixed base precomputation class
983 /// \tparam BASE class or type of an element
984 template <class GROUP_PRECOMP, class BASE_PRECOMP = DL_FixedBasePrecomputationImpl<typename GROUP_PRECOMP::Element>, class BASE = DL_GroupParameters<typename GROUP_PRECOMP::Element> >
985 class DL_GroupParametersImpl : public BASE
986 {
987 public:
988  typedef GROUP_PRECOMP GroupPrecomputation;
989  typedef typename GROUP_PRECOMP::Element Element;
990  typedef BASE_PRECOMP BasePrecomputation;
991 
992  virtual ~DL_GroupParametersImpl() {}
993 
994  /// \brief Retrieves the group precomputation
995  /// \return a const reference to the group precomputation
996  const DL_GroupPrecomputation<Element> & GetGroupPrecomputation() const {return m_groupPrecomputation;}
997 
998  /// \brief Retrieves the group precomputation
999  /// \return a const reference to the group precomputation using a fixed base
1001 
1002  /// \brief Retrieves the group precomputation
1003  /// \return a non-const reference to the group precomputation using a fixed base
1005 
1006 protected:
1007  GROUP_PRECOMP m_groupPrecomputation;
1008  BASE_PRECOMP m_gpc;
1009 };
1010 
1011 /// \brief Base class for a Discrete Log (DL) key
1012 /// \tparam T class or type of an element
1013 /// \details The element is usually an Integer, \ref ECP "ECP::Point" or \ref EC2N "EC2N::Point"
1014 template <class T>
1015 class CRYPTOPP_NO_VTABLE DL_Key
1016 {
1017 public:
1018  virtual ~DL_Key() {}
1019 
1020  /// \brief Retrieves abstract group parameters
1021  /// \return a const reference to the group parameters
1022  virtual const DL_GroupParameters<T> & GetAbstractGroupParameters() const =0;
1023  /// \brief Retrieves abstract group parameters
1024  /// \return a non-const reference to the group parameters
1025  virtual DL_GroupParameters<T> & AccessAbstractGroupParameters() =0;
1026 };
1027 
1028 /// \brief Interface for Discrete Log (DL) public keys
1029 template <class T>
1030 class CRYPTOPP_NO_VTABLE DL_PublicKey : public DL_Key<T>
1031 {
1032  typedef DL_PublicKey<T> ThisClass;
1033 
1034 public:
1035  typedef T Element;
1036 
1037  virtual ~DL_PublicKey();
1038 
1039  /// \brief Get a named value
1040  /// \param name the name of the object or value to retrieve
1041  /// \param valueType reference to a variable that receives the value
1042  /// \param pValue void pointer to a variable that receives the value
1043  /// \returns true if the value was retrieved, false otherwise
1044  /// \details GetVoidValue() retrieves the value of name if it exists.
1045  /// \note GetVoidValue() is an internal function and should be implemented
1046  /// by derived classes. Users should use one of the other functions instead.
1047  /// \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(),
1048  /// GetRequiredParameter() and GetRequiredIntParameter()
1049  bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
1050  {
1051  return GetValueHelper(this, name, valueType, pValue, &this->GetAbstractGroupParameters())
1052  CRYPTOPP_GET_FUNCTION_ENTRY(PublicElement);
1053  }
1054 
1055  /// \brief Initialize or reinitialize this key
1056  /// \param source NameValuePairs to assign
1057  void AssignFrom(const NameValuePairs &source);
1058 
1059  /// \brief Retrieves the public element
1060  /// \returns the public element
1061  virtual const Element & GetPublicElement() const {return GetPublicPrecomputation().GetBase(this->GetAbstractGroupParameters().GetGroupPrecomputation());}
1062 
1063  /// \brief Sets the public element
1064  /// \param y the public element
1065  virtual void SetPublicElement(const Element &y) {AccessPublicPrecomputation().SetBase(this->GetAbstractGroupParameters().GetGroupPrecomputation(), y);}
1066 
1067  /// \brief Exponentiates this element
1068  /// \param exponent the exponent to raise the base
1069  /// \returns the public element raised to the exponent
1070  virtual Element ExponentiatePublicElement(const Integer &exponent) const
1071  {
1072  const DL_GroupParameters<T> &params = this->GetAbstractGroupParameters();
1073  return GetPublicPrecomputation().Exponentiate(params.GetGroupPrecomputation(), exponent);
1074  }
1075 
1076  /// \brief Exponentiates an element
1077  /// \param baseExp the first exponent
1078  /// \param publicExp the second exponent
1079  /// \returns the public element raised to the exponent
1080  /// \details CascadeExponentiateBaseAndPublicElement raises the public element to
1081  /// the base element and precomputation.
1082  virtual Element CascadeExponentiateBaseAndPublicElement(const Integer &baseExp, const Integer &publicExp) const
1083  {
1084  const DL_GroupParameters<T> &params = this->GetAbstractGroupParameters();
1085  return params.GetBasePrecomputation().CascadeExponentiate(params.GetGroupPrecomputation(), baseExp, GetPublicPrecomputation(), publicExp);
1086  }
1087 
1088  /// \brief Accesses the public precomputation
1089  /// \details GetPublicPrecomputation returns a const reference, while
1090  /// AccessPublicPrecomputation returns a non-const reference. Must be
1091  /// overridden in derived classes.
1092  virtual const DL_FixedBasePrecomputation<T> & GetPublicPrecomputation() const =0;
1093 
1094  /// \brief Accesses the public precomputation
1095  /// \details GetPublicPrecomputation returns a const reference, while
1096  /// AccessPublicPrecomputation returns a non-const reference. Must be
1097  /// overridden in derived classes.
1098  virtual DL_FixedBasePrecomputation<T> & AccessPublicPrecomputation() =0;
1099 };
1100 
1101 // Out-of-line dtor due to AIX and GCC, http://github.com/weidai11/cryptopp/issues/499
1102 template<class T>
1104 
1105 /// \brief Interface for Discrete Log (DL) private keys
1106 template <class T>
1107 class CRYPTOPP_NO_VTABLE DL_PrivateKey : public DL_Key<T>
1108 {
1109  typedef DL_PrivateKey<T> ThisClass;
1110 
1111 public:
1112  typedef T Element;
1113 
1114  virtual ~DL_PrivateKey();
1115 
1116  /// \brief Initializes a public key from this key
1117  /// \param pub reference to a public key
1119  {
1121  pub.SetPublicElement(this->GetAbstractGroupParameters().ExponentiateBase(GetPrivateExponent()));
1122  }
1123 
1124  /// \brief Get a named value
1125  /// \param name the name of the object or value to retrieve
1126  /// \param valueType reference to a variable that receives the value
1127  /// \param pValue void pointer to a variable that receives the value
1128  /// \returns true if the value was retrieved, false otherwise
1129  /// \details GetVoidValue() retrieves the value of name if it exists.
1130  /// \note GetVoidValue() is an internal function and should be implemented
1131  /// by derived classes. Users should use one of the other functions instead.
1132  /// \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(),
1133  /// GetRequiredParameter() and GetRequiredIntParameter()
1134  bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
1135  {
1136  return GetValueHelper(this, name, valueType, pValue, &this->GetAbstractGroupParameters())
1137  CRYPTOPP_GET_FUNCTION_ENTRY(PrivateExponent);
1138  }
1139 
1140  /// \brief Initialize or reinitialize this key
1141  /// \param source NameValuePairs to assign
1142  void AssignFrom(const NameValuePairs &source)
1143  {
1144  this->AccessAbstractGroupParameters().AssignFrom(source);
1145  AssignFromHelper(this, source)
1146  CRYPTOPP_SET_FUNCTION_ENTRY(PrivateExponent);
1147  }
1148 
1149  /// \brief Retrieves the private exponent
1150  /// \returns the private exponent
1151  /// \details Must be overridden in derived classes.
1152  virtual const Integer & GetPrivateExponent() const =0;
1153  /// \brief Sets the private exponent
1154  /// \param x the private exponent
1155  /// \details Must be overridden in derived classes.
1156  virtual void SetPrivateExponent(const Integer &x) =0;
1157 };
1158 
1159 // Out-of-line dtor due to AIX and GCC, http://github.com/weidai11/cryptopp/issues/499
1160 template<class T>
1162 
1163 template <class T>
1165 {
1166  DL_PrivateKey<T> *pPrivateKey = NULLPTR;
1167  if (source.GetThisPointer(pPrivateKey))
1168  pPrivateKey->MakePublicKey(*this);
1169  else
1170  {
1171  this->AccessAbstractGroupParameters().AssignFrom(source);
1172  AssignFromHelper(this, source)
1173  CRYPTOPP_SET_FUNCTION_ENTRY(PublicElement);
1174  }
1175 }
1176 
1177 class OID;
1178 
1179 /// \brief Discrete Log (DL) key base implementation
1180 /// \tparam PK Key class
1181 /// \tparam GP GroupParameters class
1182 /// \tparam O OID class
1183 template <class PK, class GP, class O = OID>
1184 class DL_KeyImpl : public PK
1185 {
1186 public:
1187  typedef GP GroupParameters;
1188 
1189  virtual ~DL_KeyImpl() {}
1190 
1191  O GetAlgorithmID() const {return GetGroupParameters().GetAlgorithmID();}
1192  bool BERDecodeAlgorithmParameters(BufferedTransformation &bt)
1193  {AccessGroupParameters().BERDecode(bt); return true;}
1194  bool DEREncodeAlgorithmParameters(BufferedTransformation &bt) const
1195  {GetGroupParameters().DEREncode(bt); return true;}
1196 
1197  const GP & GetGroupParameters() const {return m_groupParameters;}
1198  GP & AccessGroupParameters() {return m_groupParameters;}
1199 
1200 private:
1201  GP m_groupParameters;
1202 };
1203 
1204 class X509PublicKey;
1205 class PKCS8PrivateKey;
1206 
1207 /// \brief Discrete Log (DL) private key base implementation
1208 /// \tparam GP GroupParameters class
1209 template <class GP>
1210 class DL_PrivateKeyImpl : public DL_PrivateKey<typename GP::Element>, public DL_KeyImpl<PKCS8PrivateKey, GP>
1211 {
1212 public:
1213  typedef typename GP::Element Element;
1214 
1215  virtual ~DL_PrivateKeyImpl() {}
1216 
1217  // GeneratableCryptoMaterial
1218  bool Validate(RandomNumberGenerator &rng, unsigned int level) const
1219  {
1221  bool pass = GetAbstractGroupParameters().Validate(rng, level);
1222 
1223  const Integer &q = GetAbstractGroupParameters().GetSubgroupOrder();
1224  const Integer &x = GetPrivateExponent();
1225 
1226  CRYPTOPP_ASSERT(x.IsPositive());
1227  CRYPTOPP_ASSERT(x < q);
1228  pass = pass && x.IsPositive() && x < q;
1229 
1230  if (level >= 1)
1231  {
1233  pass = pass && Integer::Gcd(x, q) == Integer::One();
1234  }
1235  return pass;
1236  }
1237 
1238  bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
1239  {
1240  return GetValueHelper<DL_PrivateKey<Element> >(this, name, valueType, pValue).Assignable();
1241  }
1242 
1243  void AssignFrom(const NameValuePairs &source)
1244  {
1245  AssignFromHelper<DL_PrivateKey<Element> >(this, source);
1246  }
1247 
1249  {
1250  if (!params.GetThisObject(this->AccessGroupParameters()))
1251  this->AccessGroupParameters().GenerateRandom(rng, params);
1252  Integer x(rng, Integer::One(), GetAbstractGroupParameters().GetMaxExponent());
1253  SetPrivateExponent(x);
1254  }
1255 
1256  bool SupportsPrecomputation() const {return true;}
1257 
1258  void Precompute(unsigned int precomputationStorage=16)
1259  {AccessAbstractGroupParameters().Precompute(precomputationStorage);}
1260 
1261  void LoadPrecomputation(BufferedTransformation &storedPrecomputation)
1262  {AccessAbstractGroupParameters().LoadPrecomputation(storedPrecomputation);}
1263 
1264  void SavePrecomputation(BufferedTransformation &storedPrecomputation) const
1265  {GetAbstractGroupParameters().SavePrecomputation(storedPrecomputation);}
1266 
1267  // DL_Key
1268  const DL_GroupParameters<Element> & GetAbstractGroupParameters() const {return this->GetGroupParameters();}
1269  DL_GroupParameters<Element> & AccessAbstractGroupParameters() {return this->AccessGroupParameters();}
1270 
1271  // DL_PrivateKey
1272  const Integer & GetPrivateExponent() const {return m_x;}
1273  void SetPrivateExponent(const Integer &x) {m_x = x;}
1274 
1275  // PKCS8PrivateKey
1277  {m_x.BERDecode(bt);}
1279  {m_x.DEREncode(bt);}
1280 
1281 private:
1282  Integer m_x;
1283 };
1284 
1285 template <class BASE, class SIGNATURE_SCHEME>
1287 {
1288 public:
1290 
1291  void GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &params)
1292  {
1293  BASE::GenerateRandom(rng, params);
1294 
1296  {
1297  typename SIGNATURE_SCHEME::Signer signer(*this);
1298  typename SIGNATURE_SCHEME::Verifier verifier(signer);
1299  SignaturePairwiseConsistencyTest_FIPS_140_Only(signer, verifier);
1300  }
1301  }
1302 };
1303 
1304 /// \brief Discrete Log (DL) public key base implementation
1305 /// \tparam GP GroupParameters class
1306 template <class GP>
1307 class DL_PublicKeyImpl : public DL_PublicKey<typename GP::Element>, public DL_KeyImpl<X509PublicKey, GP>
1308 {
1309 public:
1310  typedef typename GP::Element Element;
1311 
1312  virtual ~DL_PublicKeyImpl();
1313 
1314  // CryptoMaterial
1315  bool Validate(RandomNumberGenerator &rng, unsigned int level) const
1316  {
1318  bool pass = GetAbstractGroupParameters().Validate(rng, level);
1320  pass = pass && GetAbstractGroupParameters().ValidateElement(level, this->GetPublicElement(), &GetPublicPrecomputation());
1321  return pass;
1322  }
1323 
1324  bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
1325  {
1326  return GetValueHelper<DL_PublicKey<Element> >(this, name, valueType, pValue).Assignable();
1327  }
1328 
1329  void AssignFrom(const NameValuePairs &source)
1330  {
1331  AssignFromHelper<DL_PublicKey<Element> >(this, source);
1332  }
1333 
1334  bool SupportsPrecomputation() const {return true;}
1335 
1336  void Precompute(unsigned int precomputationStorage=16)
1337  {
1338  AccessAbstractGroupParameters().Precompute(precomputationStorage);
1339  AccessPublicPrecomputation().Precompute(GetAbstractGroupParameters().GetGroupPrecomputation(), GetAbstractGroupParameters().GetSubgroupOrder().BitCount(), precomputationStorage);
1340  }
1341 
1342  void LoadPrecomputation(BufferedTransformation &storedPrecomputation)
1343  {
1344  AccessAbstractGroupParameters().LoadPrecomputation(storedPrecomputation);
1345  AccessPublicPrecomputation().Load(GetAbstractGroupParameters().GetGroupPrecomputation(), storedPrecomputation);
1346  }
1347 
1348  void SavePrecomputation(BufferedTransformation &storedPrecomputation) const
1349  {
1350  GetAbstractGroupParameters().SavePrecomputation(storedPrecomputation);
1351  GetPublicPrecomputation().Save(GetAbstractGroupParameters().GetGroupPrecomputation(), storedPrecomputation);
1352  }
1353 
1354  // DL_Key
1355  const DL_GroupParameters<Element> & GetAbstractGroupParameters() const {return this->GetGroupParameters();}
1356  DL_GroupParameters<Element> & AccessAbstractGroupParameters() {return this->AccessGroupParameters();}
1357 
1358  // DL_PublicKey
1361 
1362  // non-inherited
1363  bool operator==(const DL_PublicKeyImpl<GP> &rhs) const
1364  {return this->GetGroupParameters() == rhs.GetGroupParameters() && this->GetPublicElement() == rhs.GetPublicElement();}
1365 
1366 private:
1367  typename GP::BasePrecomputation m_ypc;
1368 };
1369 
1370 // Out-of-line dtor due to AIX and GCC, http://github.com/weidai11/cryptopp/issues/499
1371 template<class GP>
1373 
1374 /// \brief Interface for Elgamal-like signature algorithms
1375 /// \tparam T Field element
1376 template <class T>
1377 class CRYPTOPP_NO_VTABLE DL_ElgamalLikeSignatureAlgorithm
1378 {
1379 public:
1380  virtual ~DL_ElgamalLikeSignatureAlgorithm() {}
1381 
1382  /// \brief Sign a message using a private key
1383  /// \param params GroupParameters
1384  /// \param privateKey private key
1385  /// \param k signing exponent
1386  /// \param e encoded message
1387  /// \param r r part of signature
1388  /// \param s s part of signature
1389  virtual void Sign(const DL_GroupParameters<T> &params, const Integer &privateKey, const Integer &k, const Integer &e, Integer &r, Integer &s) const =0;
1390 
1391  /// \brief Verify a message using a public key
1392  /// \param params GroupParameters
1393  /// \param publicKey public key
1394  /// \param e encoded message
1395  /// \param r r part of signature
1396  /// \param s s part of signature
1397  virtual bool Verify(const DL_GroupParameters<T> &params, const DL_PublicKey<T> &publicKey, const Integer &e, const Integer &r, const Integer &s) const =0;
1398 
1399  /// \brief Recover a Presignature
1400  /// \param params GroupParameters
1401  /// \param publicKey public key
1402  /// \param r r part of signature
1403  /// \param s s part of signature
1404  virtual Integer RecoverPresignature(const DL_GroupParameters<T> &params, const DL_PublicKey<T> &publicKey, const Integer &r, const Integer &s) const
1405  {
1406  CRYPTOPP_UNUSED(params); CRYPTOPP_UNUSED(publicKey); CRYPTOPP_UNUSED(r); CRYPTOPP_UNUSED(s);
1407  throw NotImplemented("DL_ElgamalLikeSignatureAlgorithm: this signature scheme does not support message recovery");
1408  MAYBE_RETURN(Integer::Zero());
1409  }
1410 
1411  /// \brief Retrieve R length
1412  /// \param params GroupParameters
1413  virtual size_t RLen(const DL_GroupParameters<T> &params) const
1414  {return params.GetSubgroupOrder().ByteCount();}
1415 
1416  /// \brief Retrieve S length
1417  /// \param params GroupParameters
1418  virtual size_t SLen(const DL_GroupParameters<T> &params) const
1419  {return params.GetSubgroupOrder().ByteCount();}
1420 
1421  /// \brief Signature scheme flag
1422  /// \returns true if the signature scheme is deterministic, false otherwise
1423  /// \details IsDeterministic() is provided for DL signers. It is used by RFC 6979 signature schemes.
1424  virtual bool IsDeterministic() const
1425  {return false;}
1426 };
1427 
1428 /// \brief Interface for deterministic signers
1429 /// \details RFC 6979 signers which generate k based on the encoded message and private key
1430 class CRYPTOPP_NO_VTABLE DeterministicSignatureAlgorithm
1431 {
1432 public:
1433  virtual ~DeterministicSignatureAlgorithm() {}
1434 
1435  /// \brief Generate k
1436  /// \param x private key
1437  /// \param q subgroup generator
1438  /// \param e encoded message
1439  virtual Integer GenerateRandom(const Integer &x, const Integer &q, const Integer &e) const =0;
1440 };
1441 
1442 /// \brief Interface for DL key agreement algorithms
1443 /// \tparam T Field element
1444 template <class T>
1445 class CRYPTOPP_NO_VTABLE DL_KeyAgreementAlgorithm
1446 {
1447 public:
1448  typedef T Element;
1449 
1450  virtual ~DL_KeyAgreementAlgorithm() {}
1451 
1452  virtual Element AgreeWithEphemeralPrivateKey(const DL_GroupParameters<Element> &params, const DL_FixedBasePrecomputation<Element> &publicPrecomputation, const Integer &privateExponent) const =0;
1453  virtual Element AgreeWithStaticPrivateKey(const DL_GroupParameters<Element> &params, const Element &publicElement, bool validateOtherPublicKey, const Integer &privateExponent) const =0;
1454 };
1455 
1456 /// \brief Interface for key derivation algorithms used in DL cryptosystems
1457 /// \tparam T Field element
1458 template <class T>
1459 class CRYPTOPP_NO_VTABLE DL_KeyDerivationAlgorithm
1460 {
1461 public:
1462  virtual ~DL_KeyDerivationAlgorithm() {}
1463 
1464  virtual bool ParameterSupported(const char *name) const
1465  {CRYPTOPP_UNUSED(name); return false;}
1466  virtual void Derive(const DL_GroupParameters<T> &groupParams, byte *derivedKey, size_t derivedLength, const T &agreedElement, const T &ephemeralPublicKey, const NameValuePairs &derivationParams) const =0;
1467 };
1468 
1469 /// \brief Interface for symmetric encryption algorithms used in DL cryptosystems
1470 class CRYPTOPP_NO_VTABLE DL_SymmetricEncryptionAlgorithm
1471 {
1472 public:
1473  virtual ~DL_SymmetricEncryptionAlgorithm() {}
1474 
1475  virtual bool ParameterSupported(const char *name) const
1476  {CRYPTOPP_UNUSED(name); return false;}
1477  virtual size_t GetSymmetricKeyLength(size_t plaintextLength) const =0;
1478  virtual size_t GetSymmetricCiphertextLength(size_t plaintextLength) const =0;
1479  virtual size_t GetMaxSymmetricPlaintextLength(size_t ciphertextLength) const =0;
1480  virtual void SymmetricEncrypt(RandomNumberGenerator &rng, const byte *key, const byte *plaintext, size_t plaintextLength, byte *ciphertext, const NameValuePairs &parameters) const =0;
1481  virtual DecodingResult SymmetricDecrypt(const byte *key, const byte *ciphertext, size_t ciphertextLength, byte *plaintext, const NameValuePairs &parameters) const =0;
1482 };
1483 
1484 /// \brief Discrete Log (DL) base interface
1485 /// \tparam KI public or private key interface
1486 template <class KI>
1487 class CRYPTOPP_NO_VTABLE DL_Base
1488 {
1489 protected:
1490  typedef KI KeyInterface;
1491  typedef typename KI::Element Element;
1492 
1493  virtual ~DL_Base() {}
1494 
1495  const DL_GroupParameters<Element> & GetAbstractGroupParameters() const {return GetKeyInterface().GetAbstractGroupParameters();}
1496  DL_GroupParameters<Element> & AccessAbstractGroupParameters() {return AccessKeyInterface().AccessAbstractGroupParameters();}
1497 
1498  virtual KeyInterface & AccessKeyInterface() =0;
1499  virtual const KeyInterface & GetKeyInterface() const =0;
1500 };
1501 
1502 /// \brief Discrete Log (DL) signature scheme base implementation
1503 /// \tparam INTFACE PK_Signer or PK_Verifier derived class
1504 /// \tparam KEY_INTFACE DL_Base key base used in the scheme
1505 /// \details DL_SignatureSchemeBase provides common functions for signers and verifiers.
1506 /// DL_Base<DL_PrivateKey> is used for signers, and DL_Base<DL_PublicKey> is used for verifiers.
1507 template <class INTFACE, class KEY_INTFACE>
1508 class CRYPTOPP_NO_VTABLE DL_SignatureSchemeBase : public INTFACE, public DL_Base<KEY_INTFACE>
1509 {
1510 public:
1511  virtual ~DL_SignatureSchemeBase() {}
1512 
1513  /// \brief Provides the signature length
1514  /// \returns signature length, in bytes
1515  /// \details SignatureLength returns the size required for <tt>r+s</tt>.
1516  size_t SignatureLength() const
1517  {
1518  return GetSignatureAlgorithm().RLen(this->GetAbstractGroupParameters())
1519  + GetSignatureAlgorithm().SLen(this->GetAbstractGroupParameters());
1520  }
1521 
1522  /// \brief Provides the maximum recoverable length
1523  /// \returns maximum recoverable length, in bytes
1524  size_t MaxRecoverableLength() const
1525  {return GetMessageEncodingInterface().MaxRecoverableLength(0, GetHashIdentifier().second, GetDigestSize());}
1526 
1527  /// \brief Provides the maximum recoverable length
1528  /// \param signatureLength the size fo the signature
1529  /// \returns maximum recoverable length based on signature length, in bytes
1530  /// \details this function is not implemented and always returns 0.
1531  size_t MaxRecoverableLengthFromSignatureLength(size_t signatureLength) const
1532  {CRYPTOPP_UNUSED(signatureLength); CRYPTOPP_ASSERT(false); return 0;} // TODO
1533 
1534  /// \brief Determines if the scheme is probabilistic
1535  /// \returns true if the scheme is probabilistic, false otherwise
1536  bool IsProbabilistic() const
1537  {return true;}
1538 
1539  /// \brief Determines if the scheme has non-recoverable part
1540  /// \returns true if the message encoding has a non-recoverable part, false otherwise.
1542  {return GetMessageEncodingInterface().AllowNonrecoverablePart();}
1543 
1544  /// \brief Determines if the scheme allows recoverable part first
1545  /// \returns true if the message encoding allows the recoverable part, false otherwise.
1547  {return GetMessageEncodingInterface().RecoverablePartFirst();}
1548 
1549 protected:
1550  size_t MessageRepresentativeLength() const {return BitsToBytes(MessageRepresentativeBitLength());}
1551  size_t MessageRepresentativeBitLength() const {return this->GetAbstractGroupParameters().GetSubgroupOrder().BitCount();}
1552 
1553  // true if the scheme conforms to RFC 6979
1554  virtual bool IsDeterministic() const {return false;}
1555 
1556  virtual const DL_ElgamalLikeSignatureAlgorithm<typename KEY_INTFACE::Element> & GetSignatureAlgorithm() const =0;
1557  virtual const PK_SignatureMessageEncodingMethod & GetMessageEncodingInterface() const =0;
1558  virtual HashIdentifier GetHashIdentifier() const =0;
1559  virtual size_t GetDigestSize() const =0;
1560 };
1561 
1562 /// \brief Discrete Log (DL) signature scheme signer base implementation
1563 /// \tparam T Field element
1564 template <class T>
1565 class CRYPTOPP_NO_VTABLE DL_SignerBase : public DL_SignatureSchemeBase<PK_Signer, DL_PrivateKey<T> >
1566 {
1567 public:
1568  virtual ~DL_SignerBase() {}
1569 
1570  /// \brief Testing interface
1571  /// \param k Integer
1572  /// \param e Integer
1573  /// \param r Integer
1574  /// \param s Integer
1575  void RawSign(const Integer &k, const Integer &e, Integer &r, Integer &s) const
1576  {
1577  const DL_ElgamalLikeSignatureAlgorithm<T> &alg = this->GetSignatureAlgorithm();
1578  const DL_GroupParameters<T> &params = this->GetAbstractGroupParameters();
1579  const DL_PrivateKey<T> &key = this->GetKeyInterface();
1580 
1581  r = params.ConvertElementToInteger(params.ExponentiateBase(k));
1582  alg.Sign(params, key.GetPrivateExponent(), k, e, r, s);
1583  }
1584 
1585  void InputRecoverableMessage(PK_MessageAccumulator &messageAccumulator, const byte *recoverableMessage, size_t recoverableMessageLength) const
1586  {
1587  PK_MessageAccumulatorBase &ma = static_cast<PK_MessageAccumulatorBase &>(messageAccumulator);
1588  ma.m_recoverableMessage.Assign(recoverableMessage, recoverableMessageLength);
1589  this->GetMessageEncodingInterface().ProcessRecoverableMessage(ma.AccessHash(),
1590  recoverableMessage, recoverableMessageLength,
1591  ma.m_presignature, ma.m_presignature.size(),
1592  ma.m_semisignature);
1593  }
1594 
1595  size_t SignAndRestart(RandomNumberGenerator &rng, PK_MessageAccumulator &messageAccumulator, byte *signature, bool restart) const
1596  {
1597  this->GetMaterial().DoQuickSanityCheck();
1598 
1599  PK_MessageAccumulatorBase &ma = static_cast<PK_MessageAccumulatorBase &>(messageAccumulator);
1600  const DL_ElgamalLikeSignatureAlgorithm<T> &alg = this->GetSignatureAlgorithm();
1601  const DL_GroupParameters<T> &params = this->GetAbstractGroupParameters();
1602  const DL_PrivateKey<T> &key = this->GetKeyInterface();
1603 
1604  SecByteBlock representative(this->MessageRepresentativeLength());
1605  this->GetMessageEncodingInterface().ComputeMessageRepresentative(
1606  rng,
1607  ma.m_recoverableMessage, ma.m_recoverableMessage.size(),
1608  ma.AccessHash(), this->GetHashIdentifier(), ma.m_empty,
1609  representative, this->MessageRepresentativeBitLength());
1610  ma.m_empty = true;
1611  Integer e(representative, representative.size());
1612 
1613  // hash message digest into random number k to prevent reusing the same k on
1614  // different messages after virtual machine rollback
1615  if (rng.CanIncorporateEntropy())
1616  rng.IncorporateEntropy(representative, representative.size());
1617 
1618  Integer k, ks;
1619  const Integer& q = params.GetSubgroupOrder();
1620  if (alg.IsDeterministic())
1621  {
1622  const Integer& x = key.GetPrivateExponent();
1623  const DeterministicSignatureAlgorithm& det = dynamic_cast<const DeterministicSignatureAlgorithm&>(alg);
1624  k = det.GenerateRandom(x, q, e);
1625  }
1626  else
1627  {
1628  k.Randomize(rng, 1, params.GetSubgroupOrder()-1);
1629  }
1630 
1631  // Due to timing attack on nonce length by Jancar
1632  // https://github.com/weidai11/cryptopp/issues/869
1633  ks = k + q;
1634  if (ks.BitCount() == q.BitCount()) {
1635  ks += q;
1636  }
1637 
1638  Integer r, s;
1639  r = params.ConvertElementToInteger(params.ExponentiateBase(ks));
1640  alg.Sign(params, key.GetPrivateExponent(), k, e, r, s);
1641 
1642  /*
1643  Integer r, s;
1644  if (this->MaxRecoverableLength() > 0)
1645  r.Decode(ma.m_semisignature, ma.m_semisignature.size());
1646  else
1647  r.Decode(ma.m_presignature, ma.m_presignature.size());
1648  alg.Sign(params, key.GetPrivateExponent(), ma.m_k, e, r, s);
1649  */
1650 
1651  const size_t rLen = alg.RLen(params);
1652  r.Encode(signature, rLen);
1653  s.Encode(signature+rLen, alg.SLen(params));
1654 
1655  if (restart)
1656  RestartMessageAccumulator(rng, ma);
1657 
1658  return this->SignatureLength();
1659  }
1660 
1661 protected:
1662  void RestartMessageAccumulator(RandomNumberGenerator &rng, PK_MessageAccumulatorBase &ma) const
1663  {
1664  // k needs to be generated before hashing for signature schemes with recovery
1665  // but to defend against VM rollbacks we need to generate k after hashing.
1666  // so this code is commented out, since no DL-based signature scheme with recovery
1667  // has been implemented in Crypto++ anyway
1668  /*
1669  const DL_ElgamalLikeSignatureAlgorithm<T> &alg = this->GetSignatureAlgorithm();
1670  const DL_GroupParameters<T> &params = this->GetAbstractGroupParameters();
1671  ma.m_k.Randomize(rng, 1, params.GetSubgroupOrder()-1);
1672  ma.m_presignature.New(params.GetEncodedElementSize(false));
1673  params.ConvertElementToInteger(params.ExponentiateBase(ma.m_k)).Encode(ma.m_presignature, ma.m_presignature.size());
1674  */
1675  CRYPTOPP_UNUSED(rng); CRYPTOPP_UNUSED(ma);
1676  }
1677 };
1678 
1679 /// \brief Discret Log (DL) Verifier base class
1680 /// \tparam T Field element
1681 template <class T>
1682 class CRYPTOPP_NO_VTABLE DL_VerifierBase : public DL_SignatureSchemeBase<PK_Verifier, DL_PublicKey<T> >
1683 {
1684 public:
1685  virtual ~DL_VerifierBase() {}
1686 
1687  void InputSignature(PK_MessageAccumulator &messageAccumulator, const byte *signature, size_t signatureLength) const
1688  {
1689  CRYPTOPP_UNUSED(signature); CRYPTOPP_UNUSED(signatureLength);
1690  PK_MessageAccumulatorBase &ma = static_cast<PK_MessageAccumulatorBase &>(messageAccumulator);
1691  const DL_ElgamalLikeSignatureAlgorithm<T> &alg = this->GetSignatureAlgorithm();
1692  const DL_GroupParameters<T> &params = this->GetAbstractGroupParameters();
1693 
1694  const size_t rLen = alg.RLen(params);
1695  ma.m_semisignature.Assign(signature, rLen);
1696  ma.m_s.Decode(signature+rLen, alg.SLen(params));
1697 
1698  this->GetMessageEncodingInterface().ProcessSemisignature(ma.AccessHash(), ma.m_semisignature, ma.m_semisignature.size());
1699  }
1700 
1701  bool VerifyAndRestart(PK_MessageAccumulator &messageAccumulator) const
1702  {
1703  this->GetMaterial().DoQuickSanityCheck();
1704 
1705  PK_MessageAccumulatorBase &ma = static_cast<PK_MessageAccumulatorBase &>(messageAccumulator);
1706  const DL_ElgamalLikeSignatureAlgorithm<T> &alg = this->GetSignatureAlgorithm();
1707  const DL_GroupParameters<T> &params = this->GetAbstractGroupParameters();
1708  const DL_PublicKey<T> &key = this->GetKeyInterface();
1709 
1710  SecByteBlock representative(this->MessageRepresentativeLength());
1711  this->GetMessageEncodingInterface().ComputeMessageRepresentative(NullRNG(), ma.m_recoverableMessage, ma.m_recoverableMessage.size(),
1712  ma.AccessHash(), this->GetHashIdentifier(), ma.m_empty,
1713  representative, this->MessageRepresentativeBitLength());
1714  ma.m_empty = true;
1715  Integer e(representative, representative.size());
1716 
1717  Integer r(ma.m_semisignature, ma.m_semisignature.size());
1718  return alg.Verify(params, key, e, r, ma.m_s);
1719  }
1720 
1721  DecodingResult RecoverAndRestart(byte *recoveredMessage, PK_MessageAccumulator &messageAccumulator) const
1722  {
1723  this->GetMaterial().DoQuickSanityCheck();
1724 
1725  PK_MessageAccumulatorBase &ma = static_cast<PK_MessageAccumulatorBase &>(messageAccumulator);
1726  const DL_ElgamalLikeSignatureAlgorithm<T> &alg = this->GetSignatureAlgorithm();
1727  const DL_GroupParameters<T> &params = this->GetAbstractGroupParameters();
1728  const DL_PublicKey<T> &key = this->GetKeyInterface();
1729 
1730  SecByteBlock representative(this->MessageRepresentativeLength());
1731  this->GetMessageEncodingInterface().ComputeMessageRepresentative(
1732  NullRNG(),
1733  ma.m_recoverableMessage, ma.m_recoverableMessage.size(),
1734  ma.AccessHash(), this->GetHashIdentifier(), ma.m_empty,
1735  representative, this->MessageRepresentativeBitLength());
1736  ma.m_empty = true;
1737  Integer e(representative, representative.size());
1738 
1739  ma.m_presignature.New(params.GetEncodedElementSize(false));
1740  Integer r(ma.m_semisignature, ma.m_semisignature.size());
1741  alg.RecoverPresignature(params, key, r, ma.m_s).Encode(ma.m_presignature, ma.m_presignature.size());
1742 
1743  return this->GetMessageEncodingInterface().RecoverMessageFromSemisignature(
1744  ma.AccessHash(), this->GetHashIdentifier(),
1745  ma.m_presignature, ma.m_presignature.size(),
1746  ma.m_semisignature, ma.m_semisignature.size(),
1747  recoveredMessage);
1748  }
1749 };
1750 
1751 /// \brief Discrete Log (DL) cryptosystem base implementation
1752 /// \tparam PK field element type
1753 /// \tparam KI public or private key interface
1754 template <class PK, class KI>
1755 class CRYPTOPP_NO_VTABLE DL_CryptoSystemBase : public PK, public DL_Base<KI>
1756 {
1757 public:
1758  typedef typename DL_Base<KI>::Element Element;
1759 
1760  virtual ~DL_CryptoSystemBase() {}
1761 
1762  size_t MaxPlaintextLength(size_t ciphertextLength) const
1763  {
1764  unsigned int minLen = this->GetAbstractGroupParameters().GetEncodedElementSize(true);
1765  return ciphertextLength < minLen ? 0 : GetSymmetricEncryptionAlgorithm().GetMaxSymmetricPlaintextLength(ciphertextLength - minLen);
1766  }
1767 
1768  size_t CiphertextLength(size_t plaintextLength) const
1769  {
1770  size_t len = GetSymmetricEncryptionAlgorithm().GetSymmetricCiphertextLength(plaintextLength);
1771  return len == 0 ? 0 : this->GetAbstractGroupParameters().GetEncodedElementSize(true) + len;
1772  }
1773 
1774  bool ParameterSupported(const char *name) const
1775  {return GetKeyDerivationAlgorithm().ParameterSupported(name) || GetSymmetricEncryptionAlgorithm().ParameterSupported(name);}
1776 
1777 protected:
1778  virtual const DL_KeyAgreementAlgorithm<Element> & GetKeyAgreementAlgorithm() const =0;
1779  virtual const DL_KeyDerivationAlgorithm<Element> & GetKeyDerivationAlgorithm() const =0;
1780  virtual const DL_SymmetricEncryptionAlgorithm & GetSymmetricEncryptionAlgorithm() const =0;
1781 };
1782 
1783 /// \brief Discrete Log (DL) decryptor base implementation
1784 /// \tparam T Field element
1785 template <class T>
1786 class CRYPTOPP_NO_VTABLE DL_DecryptorBase : public DL_CryptoSystemBase<PK_Decryptor, DL_PrivateKey<T> >
1787 {
1788 public:
1789  typedef T Element;
1790 
1791  virtual ~DL_DecryptorBase() {}
1792 
1793  DecodingResult Decrypt(RandomNumberGenerator &rng, const byte *ciphertext, size_t ciphertextLength, byte *plaintext, const NameValuePairs &parameters = g_nullNameValuePairs) const
1794  {
1795  try
1796  {
1797  CRYPTOPP_UNUSED(rng);
1798  const DL_KeyAgreementAlgorithm<T> &agreeAlg = this->GetKeyAgreementAlgorithm();
1799  const DL_KeyDerivationAlgorithm<T> &derivAlg = this->GetKeyDerivationAlgorithm();
1800  const DL_SymmetricEncryptionAlgorithm &encAlg = this->GetSymmetricEncryptionAlgorithm();
1801  const DL_GroupParameters<T> &params = this->GetAbstractGroupParameters();
1802  const DL_PrivateKey<T> &key = this->GetKeyInterface();
1803 
1804  Element q = params.DecodeElement(ciphertext, true);
1805  size_t elementSize = params.GetEncodedElementSize(true);
1806  ciphertext += elementSize;
1807  ciphertextLength -= elementSize;
1808 
1809  Element z = agreeAlg.AgreeWithStaticPrivateKey(params, q, true, key.GetPrivateExponent());
1810 
1811  SecByteBlock derivedKey(encAlg.GetSymmetricKeyLength(encAlg.GetMaxSymmetricPlaintextLength(ciphertextLength)));
1812  derivAlg.Derive(params, derivedKey, derivedKey.size(), z, q, parameters);
1813 
1814  return encAlg.SymmetricDecrypt(derivedKey, ciphertext, ciphertextLength, plaintext, parameters);
1815  }
1816  catch (DL_BadElement &)
1817  {
1818  return DecodingResult();
1819  }
1820  }
1821 };
1822 
1823 /// \brief Discrete Log (DL) encryptor base implementation
1824 /// \tparam T Field element
1825 template <class T>
1826 class CRYPTOPP_NO_VTABLE DL_EncryptorBase : public DL_CryptoSystemBase<PK_Encryptor, DL_PublicKey<T> >
1827 {
1828 public:
1829  typedef T Element;
1830 
1831  virtual ~DL_EncryptorBase() {}
1832 
1833  void Encrypt(RandomNumberGenerator &rng, const byte *plaintext, size_t plaintextLength, byte *ciphertext, const NameValuePairs &parameters = g_nullNameValuePairs) const
1834  {
1835  const DL_KeyAgreementAlgorithm<T> &agreeAlg = this->GetKeyAgreementAlgorithm();
1836  const DL_KeyDerivationAlgorithm<T> &derivAlg = this->GetKeyDerivationAlgorithm();
1837  const DL_SymmetricEncryptionAlgorithm &encAlg = this->GetSymmetricEncryptionAlgorithm();
1838  const DL_GroupParameters<T> &params = this->GetAbstractGroupParameters();
1839  const DL_PublicKey<T> &key = this->GetKeyInterface();
1840 
1841  Integer x(rng, Integer::One(), params.GetMaxExponent());
1842  Element q = params.ExponentiateBase(x);
1843  params.EncodeElement(true, q, ciphertext);
1844  unsigned int elementSize = params.GetEncodedElementSize(true);
1845  ciphertext += elementSize;
1846 
1847  Element z = agreeAlg.AgreeWithEphemeralPrivateKey(params, key.GetPublicPrecomputation(), x);
1848 
1849  SecByteBlock derivedKey(encAlg.GetSymmetricKeyLength(plaintextLength));
1850  derivAlg.Derive(params, derivedKey, derivedKey.size(), z, q, parameters);
1851 
1852  encAlg.SymmetricEncrypt(rng, derivedKey, plaintext, plaintextLength, ciphertext, parameters);
1853  }
1854 };
1855 
1856 /// \brief Discrete Log (DL) scheme options
1857 /// \tparam T1 algorithm information
1858 /// \tparam T2 group parameters for the scheme
1859 template <class T1, class T2>
1861 {
1862  typedef T1 AlgorithmInfo;
1863  typedef T2 GroupParameters;
1864  typedef typename GroupParameters::Element Element;
1865 };
1866 
1867 /// \brief Discrete Log (DL) key options
1868 /// \tparam T1 algorithm information
1869 /// \tparam T2 keys used in the scheme
1870 template <class T1, class T2>
1871 struct DL_KeyedSchemeOptions : public DL_SchemeOptionsBase<T1, typename T2::PublicKey::GroupParameters>
1872 {
1873  typedef T2 Keys;
1874  typedef typename Keys::PrivateKey PrivateKey;
1875  typedef typename Keys::PublicKey PublicKey;
1876 };
1877 
1878 /// \brief Discrete Log (DL) signature scheme options
1879 /// \tparam T1 algorithm information
1880 /// \tparam T2 keys used in the scheme
1881 /// \tparam T3 signature algorithm
1882 /// \tparam T4 message encoding method
1883 /// \tparam T5 hash function
1884 template <class T1, class T2, class T3, class T4, class T5>
1886 {
1887  typedef T3 SignatureAlgorithm;
1888  typedef T4 MessageEncodingMethod;
1889  typedef T5 HashFunction;
1890 };
1891 
1892 /// \brief Discrete Log (DL) crypto scheme options
1893 /// \tparam T1 algorithm information
1894 /// \tparam T2 keys used in the scheme
1895 /// \tparam T3 key agreement algorithm
1896 /// \tparam T4 key derivation algorithm
1897 /// \tparam T5 symmetric encryption algorithm
1898 template <class T1, class T2, class T3, class T4, class T5>
1900 {
1901  typedef T3 KeyAgreementAlgorithm;
1902  typedef T4 KeyDerivationAlgorithm;
1903  typedef T5 SymmetricEncryptionAlgorithm;
1904 };
1905 
1906 /// \brief Discrete Log (DL) base object implementation
1907 /// \tparam BASE TODO
1908 /// \tparam SCHEME_OPTIONS options for the scheme
1909 /// \tparam KEY key used in the scheme
1910 template <class BASE, class SCHEME_OPTIONS, class KEY>
1911 class CRYPTOPP_NO_VTABLE DL_ObjectImplBase : public AlgorithmImpl<BASE, typename SCHEME_OPTIONS::AlgorithmInfo>
1912 {
1913 public:
1914  typedef SCHEME_OPTIONS SchemeOptions;
1915  typedef typename KEY::Element Element;
1916 
1917  virtual ~DL_ObjectImplBase() {}
1918 
1919  PrivateKey & AccessPrivateKey() {return m_key;}
1920  PublicKey & AccessPublicKey() {return m_key;}
1921 
1922  // KeyAccessor
1923  const KEY & GetKey() const {return m_key;}
1924  KEY & AccessKey() {return m_key;}
1925 
1926 protected:
1927  typename BASE::KeyInterface & AccessKeyInterface() {return m_key;}
1928  const typename BASE::KeyInterface & GetKeyInterface() const {return m_key;}
1929 
1930  // for signature scheme
1931  HashIdentifier GetHashIdentifier() const
1932  {
1933  typedef typename SchemeOptions::MessageEncodingMethod::HashIdentifierLookup HashLookup;
1934  return HashLookup::template HashIdentifierLookup2<typename SchemeOptions::HashFunction>::Lookup();
1935  }
1936  size_t GetDigestSize() const
1937  {
1938  typedef typename SchemeOptions::HashFunction H;
1939  return H::DIGESTSIZE;
1940  }
1941 
1942 private:
1943  KEY m_key;
1944 };
1945 
1946 /// \brief Discrete Log (DL) object implementation
1947 /// \tparam BASE TODO
1948 /// \tparam SCHEME_OPTIONS options for the scheme
1949 /// \tparam KEY key used in the scheme
1950 template <class BASE, class SCHEME_OPTIONS, class KEY>
1951 class CRYPTOPP_NO_VTABLE DL_ObjectImpl : public DL_ObjectImplBase<BASE, SCHEME_OPTIONS, KEY>
1952 {
1953 public:
1954  typedef typename KEY::Element Element;
1955 
1956  virtual ~DL_ObjectImpl() {}
1957 
1958 protected:
1959  const DL_ElgamalLikeSignatureAlgorithm<Element> & GetSignatureAlgorithm() const
1961  const DL_KeyAgreementAlgorithm<Element> & GetKeyAgreementAlgorithm() const
1963  const DL_KeyDerivationAlgorithm<Element> & GetKeyDerivationAlgorithm() const
1965  const DL_SymmetricEncryptionAlgorithm & GetSymmetricEncryptionAlgorithm() const
1967  HashIdentifier GetHashIdentifier() const
1968  {return HashIdentifier();}
1969  const PK_SignatureMessageEncodingMethod & GetMessageEncodingInterface() const
1971 };
1972 
1973 /// \brief Discrete Log (DL) signer implementation
1974 /// \tparam SCHEME_OPTIONS options for the scheme
1975 template <class SCHEME_OPTIONS>
1976 class DL_SignerImpl : public DL_ObjectImpl<DL_SignerBase<typename SCHEME_OPTIONS::Element>, SCHEME_OPTIONS, typename SCHEME_OPTIONS::PrivateKey>
1977 {
1978 public:
1980  {
1982  this->RestartMessageAccumulator(rng, *p);
1983  return p.release();
1984  }
1985 };
1986 
1987 /// \brief Discrete Log (DL) verifier implementation
1988 /// \tparam SCHEME_OPTIONS options for the scheme
1989 template <class SCHEME_OPTIONS>
1990 class DL_VerifierImpl : public DL_ObjectImpl<DL_VerifierBase<typename SCHEME_OPTIONS::Element>, SCHEME_OPTIONS, typename SCHEME_OPTIONS::PublicKey>
1991 {
1992 public:
1994  {
1996  }
1997 };
1998 
1999 /// \brief Discrete Log (DL) encryptor implementation
2000 /// \tparam SCHEME_OPTIONS options for the scheme
2001 template <class SCHEME_OPTIONS>
2002 class DL_EncryptorImpl : public DL_ObjectImpl<DL_EncryptorBase<typename SCHEME_OPTIONS::Element>, SCHEME_OPTIONS, typename SCHEME_OPTIONS::PublicKey>
2003 {
2004 };
2005 
2006 /// \brief Discrete Log (DL) decryptor implementation
2007 /// \tparam SCHEME_OPTIONS options for the scheme
2008 template <class SCHEME_OPTIONS>
2009 class DL_DecryptorImpl : public DL_ObjectImpl<DL_DecryptorBase<typename SCHEME_OPTIONS::Element>, SCHEME_OPTIONS, typename SCHEME_OPTIONS::PrivateKey>
2010 {
2011 };
2012 
2013 // ********************************************************
2014 
2015 /// \brief Discrete Log (DL) simple key agreement base implementation
2016 /// \tparam T class or type
2017 template <class T>
2019 {
2020 public:
2021  typedef T Element;
2022 
2023  virtual ~DL_SimpleKeyAgreementDomainBase() {}
2024 
2025  CryptoParameters & AccessCryptoParameters() {return AccessAbstractGroupParameters();}
2026  unsigned int AgreedValueLength() const {return GetAbstractGroupParameters().GetEncodedElementSize(false);}
2027  unsigned int PrivateKeyLength() const {return GetAbstractGroupParameters().GetSubgroupOrder().ByteCount();}
2028  unsigned int PublicKeyLength() const {return GetAbstractGroupParameters().GetEncodedElementSize(true);}
2029 
2030  void GeneratePrivateKey(RandomNumberGenerator &rng, byte *privateKey) const
2031  {
2032  Integer x(rng, Integer::One(), GetAbstractGroupParameters().GetMaxExponent());
2033  x.Encode(privateKey, PrivateKeyLength());
2034  }
2035 
2036  void GeneratePublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const
2037  {
2038  CRYPTOPP_UNUSED(rng);
2039  const DL_GroupParameters<T> &params = GetAbstractGroupParameters();
2040  Integer x(privateKey, PrivateKeyLength());
2041  Element y = params.ExponentiateBase(x);
2042  params.EncodeElement(true, y, publicKey);
2043  }
2044 
2045  bool Agree(byte *agreedValue, const byte *privateKey, const byte *otherPublicKey, bool validateOtherPublicKey=true) const
2046  {
2047  try
2048  {
2049  const DL_GroupParameters<T> &params = GetAbstractGroupParameters();
2050  Integer x(privateKey, PrivateKeyLength());
2051  Element w = params.DecodeElement(otherPublicKey, validateOtherPublicKey);
2052 
2053  Element z = GetKeyAgreementAlgorithm().AgreeWithStaticPrivateKey(
2054  GetAbstractGroupParameters(), w, validateOtherPublicKey, x);
2055  params.EncodeElement(false, z, agreedValue);
2056  }
2057  catch (DL_BadElement &)
2058  {
2059  return false;
2060  }
2061  return true;
2062  }
2063 
2064  /// \brief Retrieves a reference to the group generator
2065  /// \returns const reference to the group generator
2066  const Element &GetGenerator() const {return GetAbstractGroupParameters().GetSubgroupGenerator();}
2067 
2068 protected:
2069  virtual const DL_KeyAgreementAlgorithm<Element> & GetKeyAgreementAlgorithm() const =0;
2070  virtual DL_GroupParameters<Element> & AccessAbstractGroupParameters() =0;
2071  const DL_GroupParameters<Element> & GetAbstractGroupParameters() const {return const_cast<DL_SimpleKeyAgreementDomainBase<Element> *>(this)->AccessAbstractGroupParameters();}
2072 };
2073 
2074 /// \brief Methods for avoiding "Small-Subgroup" attacks on Diffie-Hellman Key Agreement
2075 /// \details Additional methods exist and include public key validation and choice of prime p.
2076 /// \sa <A HREF="http://tools.ietf.org/html/rfc2785">Methods for Avoiding the "Small-Subgroup" Attacks on the
2077 /// Diffie-Hellman Key Agreement Method for S/MIME</A>
2079  /// \brief No cofactor multiplication applied
2081  /// \brief Cofactor multiplication compatible with ordinary Diffie-Hellman
2082  /// \details Modifies the computation of ZZ by including j (the cofactor) in the computations and is
2083  /// compatible with ordinary Diffie-Hellman.
2085  /// \brief Cofactor multiplication incompatible with ordinary Diffie-Hellman
2086  /// \details Modifies the computation of ZZ by including j (the cofactor) in the computations but is
2087  /// not compatible with ordinary Diffie-Hellman.
2089 
2093 
2094 /// \brief Diffie-Hellman key agreement algorithm
2095 template <class ELEMENT, class COFACTOR_OPTION>
2097 {
2098 public:
2099  typedef ELEMENT Element;
2100 
2101  CRYPTOPP_STATIC_CONSTEXPR const char* CRYPTOPP_API StaticAlgorithmName()
2102  {return COFACTOR_OPTION::ToEnum() == INCOMPATIBLE_COFACTOR_MULTIPLICTION ? "DHC" : "DH";}
2103 
2104  virtual ~DL_KeyAgreementAlgorithm_DH() {}
2105 
2106  Element AgreeWithEphemeralPrivateKey(const DL_GroupParameters<Element> &params, const DL_FixedBasePrecomputation<Element> &publicPrecomputation, const Integer &privateExponent) const
2107  {
2108  return publicPrecomputation.Exponentiate(params.GetGroupPrecomputation(),
2109  COFACTOR_OPTION::ToEnum() == INCOMPATIBLE_COFACTOR_MULTIPLICTION ? privateExponent*params.GetCofactor() : privateExponent);
2110  }
2111 
2112  Element AgreeWithStaticPrivateKey(const DL_GroupParameters<Element> &params, const Element &publicElement, bool validateOtherPublicKey, const Integer &privateExponent) const
2113  {
2114  if (COFACTOR_OPTION::ToEnum() == COMPATIBLE_COFACTOR_MULTIPLICTION)
2115  {
2116  const Integer &k = params.GetCofactor();
2117  return params.ExponentiateElement(publicElement,
2118  ModularArithmetic(params.GetSubgroupOrder()).Divide(privateExponent, k)*k);
2119  }
2120  else if (COFACTOR_OPTION::ToEnum() == INCOMPATIBLE_COFACTOR_MULTIPLICTION)
2121  return params.ExponentiateElement(publicElement, privateExponent*params.GetCofactor());
2122  else
2123  {
2124  CRYPTOPP_ASSERT(COFACTOR_OPTION::ToEnum() == NO_COFACTOR_MULTIPLICTION);
2125 
2126  if (!validateOtherPublicKey)
2127  return params.ExponentiateElement(publicElement, privateExponent);
2128 
2129  if (params.FastSubgroupCheckAvailable())
2130  {
2131  if (!params.ValidateElement(2, publicElement, NULLPTR))
2132  throw DL_BadElement();
2133  return params.ExponentiateElement(publicElement, privateExponent);
2134  }
2135  else
2136  {
2137  const Integer e[2] = {params.GetSubgroupOrder(), privateExponent};
2138  Element r[2];
2139  params.SimultaneousExponentiate(r, publicElement, e, 2);
2140  if (!params.IsIdentity(r[0]))
2141  throw DL_BadElement();
2142  return r[1];
2143  }
2144  }
2145  }
2146 };
2147 
2148 // ********************************************************
2149 
2150 /// \brief Template implementing constructors for public key algorithm classes
2151 template <class BASE>
2152 class CRYPTOPP_NO_VTABLE PK_FinalTemplate : public BASE
2153 {
2154 public:
2155  PK_FinalTemplate() {}
2156 
2157  PK_FinalTemplate(const CryptoMaterial &key)
2158  {this->AccessKey().AssignFrom(key);}
2159 
2161  {this->AccessKey().BERDecode(bt);}
2162 
2163  PK_FinalTemplate(const AsymmetricAlgorithm &algorithm)
2164  {this->AccessKey().AssignFrom(algorithm.GetMaterial());}
2165 
2166  PK_FinalTemplate(const Integer &v1)
2167  {this->AccessKey().Initialize(v1);}
2168 
2169  template <class T1, class T2>
2170  PK_FinalTemplate(const T1 &v1, const T2 &v2)
2171  {this->AccessKey().Initialize(v1, v2);}
2172 
2173  template <class T1, class T2, class T3>
2174  PK_FinalTemplate(const T1 &v1, const T2 &v2, const T3 &v3)
2175  {this->AccessKey().Initialize(v1, v2, v3);}
2176 
2177  template <class T1, class T2, class T3, class T4>
2178  PK_FinalTemplate(const T1 &v1, const T2 &v2, const T3 &v3, const T4 &v4)
2179  {this->AccessKey().Initialize(v1, v2, v3, v4);}
2180 
2181  template <class T1, class T2, class T3, class T4, class T5>
2182  PK_FinalTemplate(const T1 &v1, const T2 &v2, const T3 &v3, const T4 &v4, const T5 &v5)
2183  {this->AccessKey().Initialize(v1, v2, v3, v4, v5);}
2184 
2185  template <class T1, class T2, class T3, class T4, class T5, class T6>
2186  PK_FinalTemplate(const T1 &v1, const T2 &v2, const T3 &v3, const T4 &v4, const T5 &v5, const T6 &v6)
2187  {this->AccessKey().Initialize(v1, v2, v3, v4, v5, v6);}
2188 
2189  template <class T1, class T2, class T3, class T4, class T5, class T6, class T7>
2190  PK_FinalTemplate(const T1 &v1, const T2 &v2, const T3 &v3, const T4 &v4, const T5 &v5, const T6 &v6, const T7 &v7)
2191  {this->AccessKey().Initialize(v1, v2, v3, v4, v5, v6, v7);}
2192 
2193  template <class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8>
2194  PK_FinalTemplate(const T1 &v1, const T2 &v2, const T3 &v3, const T4 &v4, const T5 &v5, const T6 &v6, const T7 &v7, const T8 &v8)
2195  {this->AccessKey().Initialize(v1, v2, v3, v4, v5, v6, v7, v8);}
2196 
2197  template <class T1, class T2>
2198  PK_FinalTemplate(T1 &v1, const T2 &v2)
2199  {this->AccessKey().Initialize(v1, v2);}
2200 
2201  template <class T1, class T2, class T3>
2202  PK_FinalTemplate(T1 &v1, const T2 &v2, const T3 &v3)
2203  {this->AccessKey().Initialize(v1, v2, v3);}
2204 
2205  template <class T1, class T2, class T3, class T4>
2206  PK_FinalTemplate(T1 &v1, const T2 &v2, const T3 &v3, const T4 &v4)
2207  {this->AccessKey().Initialize(v1, v2, v3, v4);}
2208 
2209  template <class T1, class T2, class T3, class T4, class T5>
2210  PK_FinalTemplate(T1 &v1, const T2 &v2, const T3 &v3, const T4 &v4, const T5 &v5)
2211  {this->AccessKey().Initialize(v1, v2, v3, v4, v5);}
2212 
2213  template <class T1, class T2, class T3, class T4, class T5, class T6>
2214  PK_FinalTemplate(T1 &v1, const T2 &v2, const T3 &v3, const T4 &v4, const T5 &v5, const T6 &v6)
2215  {this->AccessKey().Initialize(v1, v2, v3, v4, v5, v6);}
2216 
2217  template <class T1, class T2, class T3, class T4, class T5, class T6, class T7>
2218  PK_FinalTemplate(T1 &v1, const T2 &v2, const T3 &v3, const T4 &v4, const T5 &v5, const T6 &v6, const T7 &v7)
2219  {this->AccessKey().Initialize(v1, v2, v3, v4, v5, v6, v7);}
2220 
2221  template <class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8>
2222  PK_FinalTemplate(T1 &v1, const T2 &v2, const T3 &v3, const T4 &v4, const T5 &v5, const T6 &v6, const T7 &v7, const T8 &v8)
2223  {this->AccessKey().Initialize(v1, v2, v3, v4, v5, v6, v7, v8);}
2224 };
2225 
2226 /// \brief Base class for public key encryption standard classes.
2227 /// \details These classes are used to select from variants of algorithms.
2228 /// Not all standards apply to all algorithms.
2230 
2231 /// \brief Base class for public key signature standard classes.
2232 /// \details These classes are used to select from variants of algorithms.
2233 /// Not all standards apply to all algorithms.
2235 
2236 /// \brief Trapdoor Function (TF) encryption scheme
2237 /// \tparam STANDARD standard
2238 /// \tparam KEYS keys used in the encryption scheme
2239 /// \tparam ALG_INFO algorithm information
2240 template <class KEYS, class STANDARD, class ALG_INFO>
2241 class TF_ES;
2242 
2243 template <class KEYS, class STANDARD, class ALG_INFO = TF_ES<KEYS, STANDARD, int> >
2244 class TF_ES : public KEYS
2245 {
2246  typedef typename STANDARD::EncryptionMessageEncodingMethod MessageEncodingMethod;
2247 
2248 public:
2249  /// see EncryptionStandard for a list of standards
2250  typedef STANDARD Standard;
2252 
2253  static std::string CRYPTOPP_API StaticAlgorithmName() {return std::string(KEYS::StaticAlgorithmName()) + "/" + MessageEncodingMethod::StaticAlgorithmName();}
2254 
2255  /// implements PK_Decryptor interface
2257  /// implements PK_Encryptor interface
2259 };
2260 
2261 /// \brief Trapdoor Function (TF) Signature Scheme
2262 /// \tparam STANDARD standard
2263 /// \tparam H hash function
2264 /// \tparam KEYS keys used in the signature scheme
2265 /// \tparam ALG_INFO algorithm information
2266 template <class KEYS, class STANDARD, class H, class ALG_INFO>
2267 class TF_SS;
2268 
2269 template <class KEYS, class STANDARD, class H, class ALG_INFO = TF_SS<KEYS, STANDARD, H, int> >
2270 class TF_SS : public KEYS
2271 {
2272 public:
2273  /// see SignatureStandard for a list of standards
2274  typedef STANDARD Standard;
2277 
2278  static std::string CRYPTOPP_API StaticAlgorithmName() {return std::string(KEYS::StaticAlgorithmName()) + "/" + MessageEncodingMethod::StaticAlgorithmName() + "(" + H::StaticAlgorithmName() + ")";}
2279 
2280  /// implements PK_Signer interface
2282  /// implements PK_Verifier interface
2284 };
2285 
2286 /// \brief Discrete Log (DL) signature scheme
2287 /// \tparam KEYS keys used in the signature scheme
2288 /// \tparam SA signature algorithm
2289 /// \tparam MEM message encoding method
2290 /// \tparam H hash function
2291 /// \tparam ALG_INFO algorithm information
2292 template <class KEYS, class SA, class MEM, class H, class ALG_INFO>
2293 class DL_SS;
2294 
2295 template <class KEYS, class SA, class MEM, class H, class ALG_INFO = DL_SS<KEYS, SA, MEM, H, int> >
2296 class DL_SS : public KEYS
2297 {
2299 
2300 public:
2301  static std::string StaticAlgorithmName() {return SA::StaticAlgorithmName() + std::string("/EMSA1(") + H::StaticAlgorithmName() + ")";}
2302 
2303  /// implements PK_Signer interface
2305  /// implements PK_Verifier interface
2307 };
2308 
2309 /// \brief Discrete Log (DL) encryption scheme
2310 /// \tparam KEYS keys used in the encryption scheme
2311 /// \tparam AA key agreement algorithm
2312 /// \tparam DA key derivation algorithm
2313 /// \tparam EA encryption algorithm
2314 /// \tparam ALG_INFO algorithm information
2315 template <class KEYS, class AA, class DA, class EA, class ALG_INFO>
2316 class DL_ES : public KEYS
2317 {
2319 
2320 public:
2321  /// implements PK_Decryptor interface
2323  /// implements PK_Encryptor interface
2325 };
2326 
2327 NAMESPACE_END
2328 
2329 #if CRYPTOPP_MSC_VERSION
2330 # pragma warning(pop)
2331 #endif
2332 
2333 #endif
Integer ApplyRandomizedFunction(RandomNumberGenerator &rng, const Integer &x) const
Applies the trapdoor function.
Definition: pubkey.h:137
Standard names for retrieving values by name when working with NameValuePairs.
Discrete Log (DL) key options.
Definition: pubkey.h:1871
Applies the trapdoor function, using random data if required.
Definition: pubkey.h:100
const Element & GetGenerator() const
Retrieves a reference to the group generator.
Definition: pubkey.h:2066
PK_FinalTemplate< DL_DecryptorImpl< SchemeOptions > > Decryptor
implements PK_Decryptor interface
Definition: pubkey.h:2322
virtual Element Exponentiate(const DL_GroupPrecomputation< Element > &group, const Integer &exponent) const =0
Exponentiates an element.
size_t SignatureLength() const
Provides the signature length.
Definition: pubkey.h:1516
Interface for asymmetric algorithms.
Definition: cryptlib.h:2515
virtual Integer GetCofactor() const
Retrieves the cofactor.
Definition: pubkey.h:886
Interface for message encoding method for public key signature schemes.
Definition: pubkey.h:413
Trapdoor Function (TF) encryption scheme.
Definition: pubkey.h:2241
Diffie-Hellman key agreement algorithm.
Definition: pubkey.h:2096
void SetPrivateExponent(const Integer &x)
Sets the private exponent.
Definition: pubkey.h:1273
const char * Pad()
bool
Definition: argnames.h:72
const DL_GroupPrecomputation< Element > & GetGroupPrecomputation() const
Retrieves the group precomputation.
Definition: pubkey.h:996
Restricts the instantiation of a class to one static object without locks.
Definition: misc.h:304
Discrete Log (DL) signer implementation.
Definition: pubkey.h:1976
DL_GroupPrecomputation interface.
Definition: eprecomp.h:19
void AssignFrom(const NameValuePairs &source)
Assign values to this object.
Definition: pubkey.h:1243
InvalidDataFormat(const std::string &s)
Construct an InvalidDataFormat.
Definition: cryptlib.h:218
void DEREncode(BufferedTransformation &bt) const
Encode in DER format.
Definition: integer.cpp:3446
size_t BitsToBytes(size_t bitCount)
Returns the number of 8-bit bytes or octets required for the specified number of bits.
Definition: misc.h:891
bool IsProbabilistic() const
Determines if the scheme is probabilistic.
Definition: pubkey.h:1536
Interface for deterministic signers.
Definition: pubkey.h:1430
PK_FinalTemplate< TF_VerifierImpl< SchemeOptions > > Verifier
implements PK_Verifier interface
Definition: pubkey.h:2283
void InputSignature(PK_MessageAccumulator &messageAccumulator, const byte *signature, size_t signatureLength) const
Input signature into a message accumulator.
Definition: pubkey.h:1687
size_t MaxRecoverableLengthFromSignatureLength(size_t signatureLength) const
Provides the maximum recoverable length.
Definition: pubkey.h:1531
void DEREncodePrivateKey(BufferedTransformation &bt) const
encode privateKey part of privateKeyInfo, without the OCTET STRING header
Definition: pubkey.h:1278
PK_FinalTemplate< TF_EncryptorImpl< SchemeOptions > > Encryptor
implements PK_Encryptor interface
Definition: pubkey.h:2258
static Integer CRYPTOPP_API Gcd(const Integer &a, const Integer &n)
Calculate greatest common divisor.
Definition: integer.cpp:4439
Encodes and Decodes privateKeyInfo.
Definition: asn.h:603
Trapdoor Function (TF) Signer base class.
Definition: pubkey.h:511
void BERDecodePrivateKey(BufferedTransformation &bt, bool, size_t)
decode privateKey part of privateKeyInfo, without the OCTET STRING header
Definition: pubkey.h:1276
virtual void SetSubgroupGenerator(const Element &base)
Sets the subgroup generator.
Definition: pubkey.h:836
The base for trapdoor based cryptosystems.
Definition: pubkey.h:230
Interface for Discrete Log (DL) group parameters.
Definition: pubkey.h:753
Trapdoor Function (TF) base implementation.
Definition: pubkey.h:563
Trapdoor Function (TF) Signature Scheme base class.
Definition: pubkey.h:483
Discrete Log (DL) key base implementation.
Definition: pubkey.h:1184
Converts an enumeration to a type suitable for use as a template parameter.
Definition: cryptlib.h:135
bool GetThisObject(T &object) const
Get a copy of this object or subobject.
Definition: cryptlib.h:357
Interface for message encoding method for public key signature schemes.
Definition: pubkey.h:310
Trapdoor Function (TF) signature with external reference.
Definition: pubkey.h:619
Abstract base classes that provide a uniform interface to this library.
const DL_GroupParameters< Element > & GetAbstractGroupParameters() const
Retrieves abstract group parameters.
Definition: pubkey.h:1355
virtual Integer ConvertElementToInteger(const Element &element) const =0
Converts an element to an Integer.
void MakePublicKey(DL_PublicKey< T > &pub) const
Initializes a public key from this key.
Definition: pubkey.h:1118
void GenerateAndMask(HashTransformation &hash, byte *output, size_t outputLength, const byte *input, size_t inputLength, bool mask=true) const
Generate and apply mask.
Definition: pubkey.h:718
virtual unsigned int PrivateKeyLength() const =0
Provides the size of the private key.
Message encoding method for public key encryption.
Definition: pubkey.h:208
Interface for key derivation algorithms used in DL cryptosystems.
Definition: pubkey.h:1459
virtual void Sign(const DL_GroupParameters< T > &params, const Integer &privateKey, const Integer &k, const Integer &e, Integer &r, Integer &s) const =0
Sign a message using a private key.
Classes for automatic resource management.
void SavePrecomputation(BufferedTransformation &storedPrecomputation) const
Save precomputation for later use.
Definition: pubkey.h:1264
Library configuration file.
Interface for Discrete Log (DL) private keys.
Definition: pubkey.h:1107
virtual Integer GetGroupOrder() const
Retrieves the order of the group.
Definition: pubkey.h:881
Ring of congruence classes modulo n.
Definition: modarith.h:43
Interface for random number generators.
Definition: cryptlib.h:1412
Common C++ header files.
bool Validate(RandomNumberGenerator &rng, unsigned int level) const
Check this object for errors.
Definition: pubkey.h:1218
void Randomize(RandomNumberGenerator &rng, size_t bitCount)
Set this Integer to random integer.
Definition: integer.cpp:3517
virtual Integer MaxPreimage() const
Returns the maximum size of a message before the trapdoor function is applied bound to a public key.
Definition: pubkey.h:88
bool Validate(RandomNumberGenerator &rng, unsigned int level) const
Check this object for errors.
Definition: pubkey.h:1315
Discrete Log (DL) base interface.
Definition: pubkey.h:1487
void New(size_type newSize)
Change size without preserving contents.
Definition: secblock.h:965
Trapdoor function cryptosystems decryption base class.
Definition: pubkey.h:283
Discrete Log (DL) scheme options.
Definition: pubkey.h:1860
bool IsProbabilistic() const
Determines whether an encoding method requires a random number generator.
Definition: pubkey.h:326
bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
Get a named value.
Definition: pubkey.h:783
Discrete Log (DL) encryption scheme.
Definition: pubkey.h:2316
SecBlock<byte> typedef.
Definition: secblock.h:1058
Discrete Log (DL) crypto scheme options.
Definition: pubkey.h:1899
void GeneratePrivateKey(RandomNumberGenerator &rng, byte *privateKey) const
Generate private key in this domain.
Definition: pubkey.h:2030
Classes for performing mathematics over different fields.
unsigned int AgreedValueLength() const
Provides the size of the agreed value.
Definition: pubkey.h:2026
STANDARD Standard
see SignatureStandard for a list of standards
Definition: pubkey.h:2274
Interface for buffered transformations.
Definition: cryptlib.h:1627
void RawSign(const Integer &k, const Integer &e, Integer &r, Integer &s) const
Testing interface.
Definition: pubkey.h:1575
EMSA2 padding method.
Definition: emsa2.h:71
Provides range for plaintext and ciphertext lengths.
Definition: pubkey.h:72
Interface for private keys.
Definition: cryptlib.h:2501
virtual Element ExponentiateBase(const Integer &exponent) const
Exponentiates the base.
Definition: pubkey.h:841
bool SupportsPrecomputation() const
Determines whether the object supports precomputation.
Definition: pubkey.h:1334
const DL_FixedBasePrecomputation< Element > & GetBasePrecomputation() const
Retrieves the group precomputation.
Definition: pubkey.h:1000
static const Integer &CRYPTOPP_API One()
Integer representing 1.
Definition: integer.cpp:4891
Interface for Discrete Log (DL) public keys.
Definition: pubkey.h:1030
Discret Log (DL) Verifier base class.
Definition: pubkey.h:1682
P1363 key derivation function.
Definition: pubkey.h:729
Base class for public key signature standard classes.
Definition: pubkey.h:2234
const char * PrivateExponent()
Integer.
Definition: argnames.h:35
CRYPTOPP_DLL RandomNumberGenerator &CRYPTOPP_API NullRNG()
Random Number Generator that does not produce random numbers.
Definition: cryptlib.cpp:401
CryptoParameters & AccessCryptoParameters()
Retrieves a reference to Crypto Parameters.
Definition: pubkey.h:2025
Pointer that overloads operator ->
Definition: smartptr.h:36
void Precompute(unsigned int precomputationStorage=16)
Perform precomputation.
Definition: pubkey.h:1336
virtual void SetPublicElement(const Element &y)
Sets the public element.
Definition: pubkey.h:1065
Discrete Log (DL) signature scheme.
Definition: pubkey.h:2293
unsigned int ByteCount() const
Determines the number of bytes required to represent the Integer.
Definition: integer.cpp:3350
virtual bool IsRandomized() const
Determines if the encryption algorithm is randomized.
Definition: pubkey.h:117
Base class for a Discrete Log (DL) key.
Definition: pubkey.h:1015
Interface for domains of simple key agreement protocols.
Definition: cryptlib.h:2968
Trapdoor Function (TF) encryptor options.
Definition: pubkey.h:664
Applies the inverse of the trapdoor function.
Definition: pubkey.h:178
Returns a decoding results.
Definition: cryptlib.h:277
Trapdoor Function (TF) decryptor options.
Definition: pubkey.h:657
Uses encapsulation to hide an object in derived classes.
Definition: misc.h:225
Discrete Log (DL) private key base implementation.
Definition: pubkey.h:1210
void GeneratePublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const
Generate a public key from a private key in this domain.
Definition: pubkey.h:2036
virtual const DL_GroupParameters< T > & GetAbstractGroupParameters() const =0
Retrieves abstract group parameters.
virtual const DL_FixedBasePrecomputation< T > & GetPublicPrecomputation() const =0
Accesses the public precomputation.
void Encrypt(RandomNumberGenerator &rng, const byte *plaintext, size_t plaintextLength, byte *ciphertext, const NameValuePairs &parameters=g_nullNameValuePairs) const
Encrypt a byte string.
Definition: pubkey.h:1833
DL_FixedBasePrecomputation< Element > & AccessBasePrecomputation()
Retrieves the group precomputation.
Definition: pubkey.h:1004
P1363 mask generation function.
Definition: pubkey.h:714
void LoadPrecomputation(BufferedTransformation &storedPrecomputation)
Retrieve previously saved precomputation.
Definition: pubkey.h:1261
Cofactor multiplication compatible with ordinary Diffie-Hellman.
Definition: pubkey.h:2084
Trapdoor Function (TF) encryptor options.
Definition: pubkey.h:678
PK_FinalTemplate< TF_SignerImpl< SchemeOptions > > Signer
implements PK_Signer interface
Definition: pubkey.h:2281
A method was called which was not implemented.
Definition: cryptlib.h:232
bool VerifyAndRestart(PK_MessageAccumulator &messageAccumulator) const
Check whether messageAccumulator contains a valid signature and message, and restart messageAccumulat...
Definition: pubkey.h:1701
bool RecoverablePartFirst() const
Determines if the scheme allows recoverable part first.
Definition: pubkey.h:1546
Trapdoor Function (TF) signature scheme options.
Definition: pubkey.h:640
No cofactor multiplication applied.
Definition: pubkey.h:2080
Interface for Elgamal-like signature algorithms.
Definition: pubkey.h:1377
Discrete Log (DL) signature scheme signer base implementation.
Definition: pubkey.h:1565
Interface for message encoding method for public key signature schemes.
Definition: pubkey.h:391
virtual bool Verify(const DL_GroupParameters< T > &params, const DL_PublicKey< T > &publicKey, const Integer &e, const Integer &r, const Integer &s) const =0
Verify a message using a public key.
virtual size_t RLen(const DL_GroupParameters< T > &params) const
Retrieve R length.
Definition: pubkey.h:1413
PK_MessageAccumulator * NewSignatureAccumulator(RandomNumberGenerator &rng) const
Create a new HashTransformation to accumulate the message to be signed.
Definition: pubkey.h:1979
virtual const DL_FixedBasePrecomputation< Element > & GetBasePrecomputation() const =0
Retrieves the group precomputation.
bool IsRandomized() const
Determines if the encryption algorithm is randomized.
Definition: pubkey.h:139
Interface for message encoding method for public key signature schemes.
Definition: pubkey.h:451
virtual void SimultaneousExponentiate(Element *results, const Element &base, const Integer *exponents, unsigned int exponentsCount) const =0
Exponentiates a base to multiple exponents.
void Assign(const T *ptr, size_type len)
Set contents and size from an array.
Definition: secblock.h:841
Base class for public key encryption standard classes.
Definition: pubkey.h:2229
virtual Integer MaxImage() const
Returns the maximum size of a message after the trapdoor function is applied bound to a public key.
Definition: pubkey.h:92
virtual const Element & GetSubgroupGenerator() const
Retrieves the subgroup generator.
Definition: pubkey.h:831
Discrete Log (DL) object implementation.
Definition: pubkey.h:1951
bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
Get a named value.
Definition: pubkey.h:1238
bool AllowNonrecoverablePart() const
Determines if the scheme has non-recoverable part.
Definition: pubkey.h:1541
void LoadPrecomputation(BufferedTransformation &storedPrecomputation)
Retrieve previously saved precomputation.
Definition: pubkey.h:1342
Multiple precision integer with arithmetic operations.
Definition: integer.h:49
const DL_FixedBasePrecomputation< Element > & GetPublicPrecomputation() const
Accesses the public precomputation.
Definition: pubkey.h:1359
Discrete Log (DL) verifier implementation.
Definition: pubkey.h:1990
void Precompute(unsigned int precomputationStorage=16)
Perform precomputation.
Definition: pubkey.h:1258
T1 SaturatingSubtract(const T1 &a, const T2 &b)
Performs a saturating subtract clamped at 0.
Definition: misc.h:1046
Discrete Log (DL) signature scheme base implementation.
Definition: pubkey.h:1508
Trapdoor function cryptosystems encryption base class.
Definition: pubkey.h:292
Discrete Log (DL) base object implementation.
Definition: pubkey.h:1911
Integer CalculateRandomizedInverse(RandomNumberGenerator &rng, const Integer &x) const
Applies the inverse of the trapdoor function.
Definition: pubkey.h:190
const NameValuePairs & g_nullNameValuePairs
An empty set of name-value pairs.
Definition: cryptlib.h:529
const char * SubgroupGenerator()
Integer, ECP::Point, or EC2N::Point.
Definition: argnames.h:39
Applies the trapdoor function.
Definition: pubkey.h:125
virtual bool CanIncorporateEntropy() const
Determines if a generator can accept additional entropy.
Definition: cryptlib.h:1433
bool IsRandomized() const
Determines if the decryption algorithm is randomized.
Definition: pubkey.h:196
unsigned int PublicKeyLength() const
Provides the size of the public key.
Definition: pubkey.h:2028
Discrete Log (DL) cryptosystem base implementation.
Definition: pubkey.h:1755
virtual Element DecodeElement(const byte *encoded, bool checkForGroupMembership) const =0
Decodes the element.
void Precompute(unsigned int precomputationStorage=16)
Perform precomputation.
Definition: pubkey.h:804
Mask generation function interface.
Definition: pubkey.h:685
bool Agree(byte *agreedValue, const byte *privateKey, const byte *otherPublicKey, bool validateOtherPublicKey=true) const
Derive agreed value.
Definition: pubkey.h:2045
PK_FinalTemplate< DL_EncryptorImpl< SchemeOptions > > Encryptor
implements PK_Encryptor interface
Definition: pubkey.h:2324
void AssignFrom(const NameValuePairs &source)
Initialize or reinitialize this key.
Definition: pubkey.h:1142
Public key trapdoor function default implementation.
Definition: pubkey.h:249
Trapdoor Function (TF) encryptor options.
Definition: pubkey.h:671
virtual Element ExponentiatePublicElement(const Integer &exponent) const
Exponentiates this element.
Definition: pubkey.h:1070
bool Validate(RandomNumberGenerator &rng, unsigned int level) const
Check this object for errors.
Definition: pubkey.h:765
Exception thrown when an invalid group element is encountered.
Definition: pubkey.h:743
Trapdoor Function (TF) signature scheme options.
Definition: pubkey.h:553
void AssignFrom(const NameValuePairs &source)
Initialize or reinitialize this key.
Definition: pubkey.h:1164
#define CRYPTOPP_ASSERT(exp)
Debugging and diagnostic assertion.
Definition: trap.h:69
virtual bool ValidateElement(unsigned int level, const Element &element, const DL_FixedBasePrecomputation< Element > *precomp) const =0
Check the element for errors.
CRYPTOPP_DLL bool CRYPTOPP_API FIPS_140_2_ComplianceEnabled()
Determines whether the library provides FIPS validated cryptography.
Definition: fips140.cpp:24
DecodingResult Decrypt(RandomNumberGenerator &rng, const byte *ciphertext, size_t ciphertextLength, byte *plaintext, const NameValuePairs &parameters=g_nullNameValuePairs) const
Decrypt a byte string.
Definition: pubkey.h:1793
DL_FixedBasePrecomputation interface.
Definition: eprecomp.h:60
virtual Integer GenerateRandom(const Integer &x, const Integer &q, const Integer &e) const =0
Generate k.
unsigned int BitCount() const
Determines the number of bits required to represent the Integer.
Definition: integer.cpp:3359
void Update(const byte *input, size_t length)
Updates a hash with additional input.
Definition: pubkey.h:458
Implementation of BufferedTransformation's attachment interface.
DL_GroupParameters< Element > & AccessAbstractGroupParameters()
Retrieves abstract group parameters.
Definition: pubkey.h:1356
DL_FixedBasePrecomputation< Element > & AccessPublicPrecomputation()
Accesses the public precomputation.
Definition: pubkey.h:1360
Interface for accumulating messages to be signed or verified.
Definition: cryptlib.h:2816
Interface for key agreement algorithms.
Definition: cryptlib.h:2593
Discrete Log (DL) encryptor base implementation.
Definition: pubkey.h:1826
virtual Element CascadeExponentiateBaseAndPublicElement(const Integer &baseExp, const Integer &publicExp) const
Exponentiates an element.
Definition: pubkey.h:1082
Classes for precomputation in a group.
void Encode(byte *output, size_t outputLen, Signedness sign=UNSIGNED) const
Encode in big-endian format.
Definition: integer.cpp:3424
void AssignFrom(const NameValuePairs &source)
Assign values to this object.
Definition: pubkey.h:1329
Trapdoor Function (TF) Verifier base class.
Definition: pubkey.h:521
virtual const Integer & GetPrivateExponent() const =0
Retrieves the private exponent.
PK_FinalTemplate< DL_SignerImpl< SchemeOptions > > Signer
implements PK_Signer interface
Definition: pubkey.h:2304
virtual const DL_GroupPrecomputation< Element > & GetGroupPrecomputation() const =0
Retrieves the group precomputation.
bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
Get a named value.
Definition: pubkey.h:1324
Classes and functions for the FIPS 140-2 validated library.
virtual Integer RecoverPresignature(const DL_GroupParameters< T > &params, const DL_PublicKey< T > &publicKey, const Integer &r, const Integer &s) const
Recover a Presignature.
Definition: pubkey.h:1404
size_t MaxRecoverableLength() const
Provides the maximum recoverable length.
Definition: pubkey.h:1524
PK_FinalTemplate< TF_DecryptorImpl< SchemeOptions > > Decryptor
implements PK_Decryptor interface
Definition: pubkey.h:2256
Interface for hash functions and data processing part of MACs.
Definition: cryptlib.h:1113
Interface for crypto material, such as public and private keys, and crypto parameters.
Definition: cryptlib.h:2354
virtual void EncodeElement(bool reversible, const Element &element, byte *encoded) const =0
Encodes the element.
CofactorMultiplicationOption
Methods for avoiding "Small-Subgroup" attacks on Diffie-Hellman Key Agreement.
Definition: pubkey.h:2078
unsigned int PrivateKeyLength() const
Provides the size of the private key.
Definition: pubkey.h:2027
DL_GroupParameters< Element > & AccessAbstractGroupParameters()
Retrieves abstract group parameters.
Definition: pubkey.h:1269
virtual unsigned int GetEncodedElementSize(bool reversible) const =0
Retrieves the encoded element's size.
void Decode(const byte *input, size_t inputLen, Signedness sign=UNSIGNED)
Decode from big-endian byte array.
Definition: integer.cpp:3368
Discrete Log (DL) encryptor implementation.
Definition: pubkey.h:2002
bool SupportsPrecomputation() const
Determines whether the object supports precomputation.
Definition: pubkey.h:794
Discrete Log (DL) public key base implementation.
Definition: pubkey.h:1307
Multiple precision integer with arithmetic operations.
Cofactor multiplication incompatible with ordinary Diffie-Hellman.
Definition: pubkey.h:2088
static const Integer &CRYPTOPP_API Zero()
Integer representing 0.
Definition: integer.cpp:4879
Interface for crypto prameters.
Definition: cryptlib.h:2506
bool GetThisPointer(T *&ptr) const
Get a pointer to this object.
Definition: cryptlib.h:366
virtual Integer GetMaxExponent() const =0
Retrieves the maximum exponent for the group.
Discrete Log (DL) decryptor implementation.
Definition: pubkey.h:2009
void InputRecoverableMessage(PK_MessageAccumulator &messageAccumulator, const byte *recoverableMessage, size_t recoverableMessageLength) const
Input a recoverable message to an accumulator.
Definition: pubkey.h:1585
void BERDecode(const byte *input, size_t inputLen)
Decode from BER format.
Definition: integer.cpp:3453
size_t SignAndRestart(RandomNumberGenerator &rng, PK_MessageAccumulator &messageAccumulator, byte *signature, bool restart) const
Sign and restart messageAccumulator.
Definition: pubkey.h:1595
Class file for performing modular arithmetic.
Interface for public keys.
Definition: cryptlib.h:2496
Crypto++ library namespace.
PK_MessageAccumulator * NewVerificationAccumulator() const
Create a new HashTransformation to accumulate the message to be verified.
Definition: pubkey.h:1993
Applies the inverse of the trapdoor function, using random data if required.
Definition: pubkey.h:154
virtual const Element & GetPublicElement() const
Retrieves the public element.
Definition: pubkey.h:1061
Interface for symmetric encryption algorithms used in DL cryptosystems.
Definition: pubkey.h:1470
bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
Get a named value.
Definition: pubkey.h:1134
Base implementation of Discrete Log (DL) group parameters.
Definition: pubkey.h:985
void GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &params)
Generate a random key or crypto parameters.
Definition: pubkey.h:1248
virtual bool IsRandomized() const
Determines if the decryption algorithm is randomized.
Definition: pubkey.h:170
Encodes and decodes subjectPublicKeyInfo.
Definition: asn.h:580
Trapdoor function cryptosystem base class.
Definition: pubkey.h:267
virtual DL_GroupParameters< T > & AccessAbstractGroupParameters()=0
Retrieves abstract group parameters.
Input data was received that did not conform to expected format.
Definition: cryptlib.h:212
Trapdoor Function (TF) scheme options.
Definition: pubkey.h:538
void LoadPrecomputation(BufferedTransformation &storedPrecomputation)
Retrieve previously saved precomputation.
Definition: pubkey.h:813
bool SupportsPrecomputation() const
Determines whether the object supports precomputation.
Definition: pubkey.h:1256
PK_FinalTemplate< DL_VerifierImpl< SchemeOptions > > Verifier
implements PK_Verifier interface
Definition: pubkey.h:2306
Discrete Log (DL) signature scheme options.
Definition: pubkey.h:1885
virtual Element ExponentiateElement(const Element &base, const Integer &exponent) const
Exponentiates an element.
Definition: pubkey.h:851
Object Identifier.
Definition: asn.h:166
Interface for message encoding method for public key signature schemes.
Definition: pubkey.h:402
virtual bool IsDeterministic() const
Signature scheme flag.
Definition: pubkey.h:1424
const char * SubgroupOrder()
Integer.
Definition: argnames.h:37
Discrete Log (DL) decryptor base implementation.
Definition: pubkey.h:1786
Interface for message encoding method for public key signature schemes.
Definition: pubkey.h:473
const char * PublicElement()
Integer.
Definition: argnames.h:36
Interface for DL key agreement algorithms.
Definition: pubkey.h:1445
DecodingResult RecoverAndRestart(byte *recoveredMessage, PK_MessageAccumulator &messageAccumulator) const
Recover a message from its signature.
Definition: pubkey.h:1721
const Integer & GetPrivateExponent() const
Retrieves the private exponent.
Definition: pubkey.h:1272
const T & Ref(...) const
Return a reference to the inner Singleton object.
Definition: misc.h:325
size_type size() const
Provides the count of elements in the SecBlock.
Definition: secblock.h:797
Discrete Log (DL) simple key agreement base implementation.
Definition: pubkey.h:2018
bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
Get a named value.
Definition: pubkey.h:1049
virtual bool IsIdentity(const Element &element) const =0
Determines if an element is an identity.
virtual size_t SLen(const DL_GroupParameters< T > &params) const
Retrieve S length.
Definition: pubkey.h:1418
STANDARD Standard
see EncryptionStandard for a list of standards
Definition: pubkey.h:2250
virtual void IncorporateEntropy(const byte *input, size_t length)
Update RNG state with additional unpredictable values.
Definition: cryptlib.h:1425
void SavePrecomputation(BufferedTransformation &storedPrecomputation) const
Save precomputation for later use.
Definition: pubkey.h:823
void SavePrecomputation(BufferedTransformation &storedPrecomputation) const
Save precomputation for later use.
Definition: pubkey.h:1348
Interface for message encoding method for public key signature schemes.
Definition: pubkey.h:425
const DL_GroupParameters< Element > & GetAbstractGroupParameters() const
Retrieves abstract group parameters.
Definition: pubkey.h:1268
Interface for retrieving values given their names.
Definition: cryptlib.h:321
Template implementing constructors for public key algorithm classes.
Definition: pubkey.h:2152
Trapdoor Function (TF) Signature Scheme.
Definition: pubkey.h:2267
virtual const Integer & GetSubgroupOrder() const =0
Retrieves the subgroup order.
Base class information.
Definition: simple.h:39