Crypto++  8.5
Free C++ class library of cryptographic schemes
gfpcrypt.h
Go to the documentation of this file.
1 // gfpcrypt.h - originally written and placed in the public domain by Wei Dai
2 // RFC6979 deterministic signatures added by Douglas Roark
3 // ECGDSA added by Jeffrey Walton
4 
5 /// \file gfpcrypt.h
6 /// \brief Classes and functions for schemes based on Discrete Logs (DL) over GF(p)
7 
8 #ifndef CRYPTOPP_GFPCRYPT_H
9 #define CRYPTOPP_GFPCRYPT_H
10 
11 #include "config.h"
12 
13 #if CRYPTOPP_MSC_VERSION
14 # pragma warning(push)
15 # pragma warning(disable: 4189 4231 4275)
16 #endif
17 
18 #include "cryptlib.h"
19 #include "pubkey.h"
20 #include "integer.h"
21 #include "modexppc.h"
22 #include "algparam.h"
23 #include "smartptr.h"
24 #include "sha.h"
25 #include "asn.h"
26 #include "hmac.h"
27 #include "misc.h"
28 
29 NAMESPACE_BEGIN(CryptoPP)
30 
32 
33 /// \brief Integer-based GroupParameters specialization
34 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE DL_GroupParameters_IntegerBased : public ASN1CryptoMaterial<DL_GroupParameters<Integer> >
35 {
37 
38 public:
40 
41  /// \brief Initialize a group parameters over integers
42  /// \param params the group parameters
44  {Initialize(params.GetModulus(), params.GetSubgroupOrder(), params.GetSubgroupGenerator());}
45 
46  /// \brief Create a group parameters over integers
47  /// \param rng a RandomNumberGenerator derived class
48  /// \param pbits the size of p, in bits
49  /// \details This function overload of Initialize() creates a new private key because it
50  /// takes a RandomNumberGenerator() as a parameter. If you have an existing keypair,
51  /// then use one of the other Initialize() overloads.
52  void Initialize(RandomNumberGenerator &rng, unsigned int pbits)
53  {GenerateRandom(rng, MakeParameters("ModulusSize", (int)pbits));}
54 
55  /// \brief Initialize a group parameters over integers
56  /// \param p the modulus
57  /// \param g the generator
58  void Initialize(const Integer &p, const Integer &g)
59  {SetModulusAndSubgroupGenerator(p, g); SetSubgroupOrder(ComputeGroupOrder(p)/2);}
60 
61  /// \brief Initialize a group parameters over integers
62  /// \param p the modulus
63  /// \param q the subgroup order
64  /// \param g the generator
65  void Initialize(const Integer &p, const Integer &q, const Integer &g)
66  {SetModulusAndSubgroupGenerator(p, g); SetSubgroupOrder(q);}
67 
68  // ASN1Object interface
70  void DEREncode(BufferedTransformation &bt) const;
71 
72  /// \brief Generate a random key
73  /// \param rng a RandomNumberGenerator to produce keying material
74  /// \param alg additional initialization parameters
75  /// \details Recognised NameValuePairs are ModulusSize and
76  /// SubgroupOrderSize (optional)
77  /// \throw KeyingErr if a key can't be generated or algorithm parameters
78  /// are invalid
79  void GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &alg);
80 
81  /// \brief Get a named value
82  /// \param name the name of the object or value to retrieve
83  /// \param valueType reference to a variable that receives the value
84  /// \param pValue void pointer to a variable that receives the value
85  /// \return true if the value was retrieved, false otherwise
86  /// \details GetVoidValue() retrieves the value of name if it exists.
87  /// \note GetVoidValue() is an internal function and should be implemented
88  /// by derived classes. Users should use one of the other functions instead.
89  /// \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(),
90  /// GetRequiredParameter() and GetRequiredIntParameter()
91  bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const;
92 
93  /// \brief Initialize or reinitialize this key
94  /// \param source NameValuePairs to assign
95  void AssignFrom(const NameValuePairs &source);
96 
97  // DL_GroupParameters
98  const Integer & GetSubgroupOrder() const {return m_q;}
99  Integer GetGroupOrder() const {return GetFieldType() == 1 ? GetModulus()-Integer::One() : GetModulus()+Integer::One();}
100  bool ValidateGroup(RandomNumberGenerator &rng, unsigned int level) const;
101  bool ValidateElement(unsigned int level, const Integer &element, const DL_FixedBasePrecomputation<Integer> *precomp) const;
102 
103  /// \brief Determine if subgroup membership check is fast
104  /// \return true or false
105  bool FastSubgroupCheckAvailable() const {return GetCofactor() == 2;}
106 
107  /// \brief Encodes the element
108  /// \param reversible flag indicating the encoding format
109  /// \param element reference to the element to encode
110  /// \param encoded destination byte array for the encoded element
111  /// \details EncodeElement() must be implemented in a derived class.
112  /// \pre <tt>COUNTOF(encoded) == GetEncodedElementSize()</tt>
113  /// \sa GetEncodedElementSize(), DecodeElement(), <A
114  /// HREF="http://github.com/weidai11/cryptopp/issues/40">Cygwin
115  /// i386 crash at -O3</A>
116  void EncodeElement(bool reversible, const Element &element, byte *encoded) const;
117 
118  /// \brief Retrieve the encoded element's size
119  /// \param reversible flag indicating the encoding format
120  /// \return encoded element's size, in bytes
121  /// \details The format of the encoded element varies by the underlying
122  /// type of the element and the reversible flag.
123  /// \sa EncodeElement(), DecodeElement()
124  unsigned int GetEncodedElementSize(bool reversible) const;
125 
126  /// \brief Decodes the element
127  /// \param encoded byte array with the encoded element
128  /// \param checkForGroupMembership flag indicating if the element should be validated
129  /// \return Element after decoding
130  /// \details DecodeElement() must be implemented in a derived class.
131  /// \pre <tt>COUNTOF(encoded) == GetEncodedElementSize()</tt>
132  /// \sa GetEncodedElementSize(), EncodeElement()
133  Integer DecodeElement(const byte *encoded, bool checkForGroupMembership) const;
134 
135  /// \brief Converts an element to an Integer
136  /// \param element the element to convert to an Integer
137  /// \return Element after converting to an Integer
138  /// \details ConvertElementToInteger() must be implemented in a derived class.
140  {return element;}
141 
142  /// \brief Retrieve the maximum exponent for the group
143  /// \return the maximum exponent for the group
144  Integer GetMaxExponent() const;
145 
146  /// \brief Retrieve the OID of the algorithm
147  /// \return OID of the algorithm
148  OID GetAlgorithmID() const;
149 
150  /// \brief Retrieve the modulus for the group
151  /// \return the modulus for the group
152  virtual const Integer & GetModulus() const =0;
153 
154  /// \brief Set group parameters
155  /// \param p the prime modulus
156  /// \param g the group generator
157  virtual void SetModulusAndSubgroupGenerator(const Integer &p, const Integer &g) =0;
158 
159  /// \brief Set subgroup order
160  /// \param q the subgroup order
161  void SetSubgroupOrder(const Integer &q)
162  {m_q = q; ParametersChanged();}
163 
164  static std::string CRYPTOPP_API StaticAlgorithmNamePrefix() {return "";}
165 
166 protected:
167  Integer ComputeGroupOrder(const Integer &modulus) const
168  {return modulus-(GetFieldType() == 1 ? 1 : -1);}
169 
170  // GF(p) = 1, GF(p^2) = 2
171  virtual int GetFieldType() const =0;
172  virtual unsigned int GetDefaultSubgroupOrderSize(unsigned int modulusSize) const;
173 
174 private:
175  Integer m_q;
176 };
177 
178 /// \brief Integer-based GroupParameters default implementation
179 /// \tparam GROUP_PRECOMP group parameters precomputation specialization
180 /// \tparam BASE_PRECOMP base class precomputation specialization
181 template <class GROUP_PRECOMP, class BASE_PRECOMP = DL_FixedBasePrecomputationImpl<typename GROUP_PRECOMP::Element> >
182 class CRYPTOPP_NO_VTABLE DL_GroupParameters_IntegerBasedImpl : public DL_GroupParametersImpl<GROUP_PRECOMP, BASE_PRECOMP, DL_GroupParameters_IntegerBased>
183 {
185 
186 public:
187  typedef typename GROUP_PRECOMP::Element Element;
188 
190 
191  // GeneratibleCryptoMaterial interface
192  bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
193  {return GetValueHelper<DL_GroupParameters_IntegerBased>(this, name, valueType, pValue).Assignable();}
194 
195  void AssignFrom(const NameValuePairs &source)
196  {AssignFromHelper<DL_GroupParameters_IntegerBased>(this, source);}
197 
198  // DL_GroupParameters
199  const DL_FixedBasePrecomputation<Element> & GetBasePrecomputation() const {return this->m_gpc;}
201 
202  // IntegerGroupParameters
203  /// \brief Retrieve the modulus for the group
204  /// \return the modulus for the group
205  const Integer & GetModulus() const {return this->m_groupPrecomputation.GetModulus();}
206 
207  /// \brief Retrieves a reference to the group generator
208  /// \return const reference to the group generator
209  const Integer & GetGenerator() const {return this->m_gpc.GetBase(this->GetGroupPrecomputation());}
210 
211  void SetModulusAndSubgroupGenerator(const Integer &p, const Integer &g) // these have to be set together
212  {this->m_groupPrecomputation.SetModulus(p); this->m_gpc.SetBase(this->GetGroupPrecomputation(), g); this->ParametersChanged();}
213 
214  // non-inherited
216  {return GetModulus() == rhs.GetModulus() && GetGenerator() == rhs.GetGenerator() && this->GetSubgroupOrder() == rhs.GetSubgroupOrder();}
218  {return !operator==(rhs);}
219 };
220 
222 
223 /// \brief GF(p) group parameters
224 class CRYPTOPP_DLL DL_GroupParameters_GFP : public DL_GroupParameters_IntegerBasedImpl<ModExpPrecomputation>
225 {
226 public:
227  virtual ~DL_GroupParameters_GFP() {}
228 
229  /// \brief Determines if an element is an identity
230  /// \param element element to check
231  /// \return true if the element is an identity, false otherwise
232  /// \details The identity element or or neutral element is a special element
233  /// in a group that leaves other elements unchanged when combined with it.
234  /// \details IsIdentity() must be implemented in a derived class.
235  bool IsIdentity(const Integer &element) const {return element == Integer::One();}
236 
237  /// \brief Exponentiates a base to multiple exponents
238  /// \param results an array of Elements
239  /// \param base the base to raise to the exponents
240  /// \param exponents an array of exponents
241  /// \param exponentsCount the number of exponents in the array
242  /// \details SimultaneousExponentiate() raises the base to each exponent in
243  /// the exponents array and stores the result at the respective position in
244  /// the results array.
245  /// \details SimultaneousExponentiate() must be implemented in a derived class.
246  /// \pre <tt>COUNTOF(results) == exponentsCount</tt>
247  /// \pre <tt>COUNTOF(exponents) == exponentsCount</tt>
248  void SimultaneousExponentiate(Element *results, const Element &base, const Integer *exponents, unsigned int exponentsCount) const;
249 
250  /// \brief Get a named value
251  /// \param name the name of the object or value to retrieve
252  /// \param valueType reference to a variable that receives the value
253  /// \param pValue void pointer to a variable that receives the value
254  /// \return true if the value was retrieved, false otherwise
255  /// \details GetVoidValue() retrieves the value of name if it exists.
256  /// \note GetVoidValue() is an internal function and should be implemented
257  /// by derived classes. Users should use one of the other functions instead.
258  /// \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(),
259  /// GetRequiredParameter() and GetRequiredIntParameter()
260  bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
261  {
262  return GetValueHelper<DL_GroupParameters_IntegerBased>(this, name, valueType, pValue).Assignable();
263  }
264 
265  // used by MQV
266  Element MultiplyElements(const Element &a, const Element &b) const;
267  Element CascadeExponentiate(const Element &element1, const Integer &exponent1, const Element &element2, const Integer &exponent2) const;
268 
269 protected:
270  int GetFieldType() const {return 1;}
271 };
272 
273 /// \brief GF(p) group parameters that default to safe primes
275 {
276 public:
278 
280 
281 protected:
282  unsigned int GetDefaultSubgroupOrderSize(unsigned int modulusSize) const {return modulusSize-1;}
283 };
284 
285 /// \brief GDSA algorithm
286 /// \tparam T FieldElement type or class
287 /// \details FieldElement <tt>T</tt> can be Integer, ECP or EC2N.
288 template <class T>
290 {
291 public:
292  CRYPTOPP_STATIC_CONSTEXPR const char* CRYPTOPP_API StaticAlgorithmName() {return "DSA-1363";}
293 
294  virtual ~DL_Algorithm_GDSA() {}
295 
296  void Sign(const DL_GroupParameters<T> &params, const Integer &x, const Integer &k, const Integer &e, Integer &r, Integer &s) const
297  {
298  const Integer &q = params.GetSubgroupOrder();
299  r %= q;
300  Integer kInv = k.InverseMod(q);
301  s = (kInv * (x*r + e)) % q;
302  CRYPTOPP_ASSERT(!!r && !!s);
303  }
304 
305  bool Verify(const DL_GroupParameters<T> &params, const DL_PublicKey<T> &publicKey, const Integer &e, const Integer &r, const Integer &s) const
306  {
307  const Integer &q = params.GetSubgroupOrder();
308  if (r>=q || r<1 || s>=q || s<1)
309  return false;
310 
311  Integer w = s.InverseMod(q);
312  Integer u1 = (e * w) % q;
313  Integer u2 = (r * w) % q;
314  // verify r == (g^u1 * y^u2 mod p) mod q
315  return r == params.ConvertElementToInteger(publicKey.CascadeExponentiateBaseAndPublicElement(u1, u2)) % q;
316  }
317 };
318 
319 /// \brief DSA signature algorithm based on RFC 6979
320 /// \tparam T FieldElement type or class
321 /// \tparam H HashTransformation derived class
322 /// \details FieldElement <tt>T</tt> can be Integer, ECP or EC2N.
323 /// \sa <a href="http://tools.ietf.org/rfc/rfc6979.txt">RFC 6979, Deterministic Usage of the
324 /// Digital Signature Algorithm (DSA) and Elliptic Curve Digital Signature Algorithm (ECDSA)</a>
325 /// \since Crypto++ 6.0
326 template <class T, class H>
328 {
329 public:
330  CRYPTOPP_STATIC_CONSTEXPR const char* CRYPTOPP_API StaticAlgorithmName() {return "DSA-RFC6979";}
331 
332  virtual ~DL_Algorithm_DSA_RFC6979() {}
333 
334  bool IsProbabilistic() const
335  {return false;}
336  bool IsDeterministic() const
337  {return true;}
338 
339  // Deterministic K
340  Integer GenerateRandom(const Integer &x, const Integer &q, const Integer &e) const
341  {
342  static const byte zero = 0, one = 1;
343  const size_t qlen = q.BitCount();
344  const size_t rlen = BitsToBytes(qlen);
345 
346  // Step (a) - formatted E(m)
348  e.Encode(BH, BH.size());
349  BH = bits2octets(BH, q);
350 
351  // Step (a) - private key to byte array
352  SecByteBlock BX(STDMAX(rlen, x.MinEncodedSize()));
353  x.Encode(BX, BX.size());
354 
355  // Step (b)
356  SecByteBlock V(H::DIGESTSIZE);
357  std::fill(V.begin(), V.begin()+H::DIGESTSIZE, one);
358 
359  // Step (c)
360  SecByteBlock K(H::DIGESTSIZE);
361  std::fill(K.begin(), K.begin()+H::DIGESTSIZE, zero);
362 
363  // Step (d)
364  m_hmac.SetKey(K, K.size());
365  m_hmac.Update(V, V.size());
366  m_hmac.Update(&zero, 1);
367  m_hmac.Update(BX, BX.size());
368  m_hmac.Update(BH, BH.size());
369  m_hmac.TruncatedFinal(K, K.size());
370 
371  // Step (e)
372  m_hmac.SetKey(K, K.size());
373  m_hmac.Update(V, V.size());
374  m_hmac.TruncatedFinal(V, V.size());
375 
376  // Step (f)
377  m_hmac.SetKey(K, K.size());
378  m_hmac.Update(V, V.size());
379  m_hmac.Update(&one, 1);
380  m_hmac.Update(BX, BX.size());
381  m_hmac.Update(BH, BH.size());
382  m_hmac.TruncatedFinal(K, K.size());
383 
384  // Step (g)
385  m_hmac.SetKey(K, K.size());
386  m_hmac.Update(V, V.size());
387  m_hmac.TruncatedFinal(V, V.size());
388 
389  Integer k;
390  SecByteBlock temp(rlen);
391  for (;;)
392  {
393  // We want qlen bits, but we support only hash functions with an output length
394  // multiple of 8; hence, we will gather rlen bits, i.e., rolen octets.
395  size_t toff = 0;
396  while (toff < rlen)
397  {
398  m_hmac.Update(V, V.size());
399  m_hmac.TruncatedFinal(V, V.size());
400 
401  size_t cc = STDMIN(V.size(), temp.size() - toff);
402  memcpy_s(temp+toff, temp.size() - toff, V, cc);
403  toff += cc;
404  }
405 
406  k = bits2int(temp, qlen);
407  if (k > 0 && k < q)
408  break;
409 
410  // k is not in the proper range; update K and V, and loop.
411  m_hmac.Update(V, V.size());
412  m_hmac.Update(&zero, 1);
413  m_hmac.TruncatedFinal(K, K.size());
414 
415  m_hmac.SetKey(K, K.size());
416  m_hmac.Update(V, V.size());
417  m_hmac.TruncatedFinal(V, V.size());
418  }
419 
420  return k;
421  }
422 
423 protected:
424 
425  Integer bits2int(const SecByteBlock& bits, size_t qlen) const
426  {
427  Integer ret(bits, bits.size());
428  size_t blen = bits.size()*8;
429 
430  if (blen > qlen)
431  ret >>= blen - qlen;
432 
433  return ret;
434  }
435 
436  // RFC 6979 support function. Takes an integer and converts it into bytes that
437  // are the same length as an elliptic curve's order.
438  SecByteBlock int2octets(const Integer& val, size_t rlen) const
439  {
440  SecByteBlock block(val.MinEncodedSize());
441  val.Encode(block, val.MinEncodedSize());
442 
443  if (block.size() == rlen)
444  return block;
445 
446  // The least significant bytes are the ones we need to preserve.
447  SecByteBlock t(rlen);
448  if (block.size() > rlen)
449  {
450  size_t offset = block.size() - rlen;
451  std::memcpy(t, block + offset, rlen);
452  }
453  else // block.size() < rlen
454  {
455  size_t offset = rlen - block.size();
456  memset(t, '\x00', offset);
457  std::memcpy(t + offset, block, rlen - offset);
458  }
459 
460  return t;
461  }
462 
463  // Turn a stream of bits into a set of bytes with the same length as an elliptic
464  // curve's order.
465  SecByteBlock bits2octets(const SecByteBlock& in, const Integer& q) const
466  {
467  Integer b2 = bits2int(in, q.BitCount());
468  Integer b1 = b2 - q;
469  return int2octets(b1.IsNegative() ? b2 : b1, q.ByteCount());
470  }
471 
472 private:
473  mutable H m_hash;
474  mutable HMAC<H> m_hmac;
475 };
476 
477 /// \brief German Digital Signature Algorithm
478 /// \tparam T FieldElement type or class
479 /// \details FieldElement <tt>T</tt> can be Integer, ECP or EC2N.
480 /// \details The Digital Signature Scheme ECGDSA does not define the algorithm over integers. Rather, the
481 /// signature algorithm is only defined over elliptic curves. However, the library design is such that the
482 /// generic algorithm reside in <tt>gfpcrypt.h</tt>.
483 /// \sa Erwin Hess, Marcus Schafheutle, and Pascale Serf <A HREF="http://www.teletrust.de/fileadmin/files/oid/ecgdsa_final.pdf">
484 /// The Digital Signature Scheme ECGDSA (October 24, 2006)</A>
485 template <class T>
487 {
488 public:
489  CRYPTOPP_STATIC_CONSTEXPR const char* CRYPTOPP_API StaticAlgorithmName() {return "GDSA-ISO15946";}
490 
491  virtual ~DL_Algorithm_GDSA_ISO15946() {}
492 
493  void Sign(const DL_GroupParameters<T> &params, const Integer &x, const Integer &k, const Integer &e, Integer &r, Integer &s) const
494  {
495  const Integer &q = params.GetSubgroupOrder();
496  // r = x(k * G) mod q
497  r = params.ConvertElementToInteger(params.ExponentiateBase(k)) % q;
498  // s = (k * r - h(m)) * d_A mod q
499  s = (k * r - e) * x % q;
500  CRYPTOPP_ASSERT(!!r && !!s);
501  }
502 
503  bool Verify(const DL_GroupParameters<T> &params, const DL_PublicKey<T> &publicKey, const Integer &e, const Integer &r, const Integer &s) const
504  {
505  const Integer &q = params.GetSubgroupOrder();
506  if (r>=q || r<1 || s>=q || s<1)
507  return false;
508 
509  const Integer& rInv = r.InverseMod(q);
510  const Integer u1 = (rInv * e) % q;
511  const Integer u2 = (rInv * s) % q;
512  // verify x(G^u1 + P_A^u2) mod q
513  return r == params.ConvertElementToInteger(publicKey.CascadeExponentiateBaseAndPublicElement(u1, u2)) % q;
514  }
515 };
516 
523 
524 /// \brief NR algorithm
525 /// \tparam T FieldElement type or class
526 /// \details FieldElement <tt>T</tt> can be Integer, ECP or EC2N.
527 template <class T>
529 {
530 public:
531  CRYPTOPP_STATIC_CONSTEXPR const char* CRYPTOPP_API StaticAlgorithmName() {return "NR";}
532 
533  virtual ~DL_Algorithm_NR() {}
534 
535  void Sign(const DL_GroupParameters<T> &params, const Integer &x, const Integer &k, const Integer &e, Integer &r, Integer &s) const
536  {
537  const Integer &q = params.GetSubgroupOrder();
538  r = (r + e) % q;
539  s = (k - x*r) % q;
540  CRYPTOPP_ASSERT(!!r);
541  }
542 
543  bool Verify(const DL_GroupParameters<T> &params, const DL_PublicKey<T> &publicKey, const Integer &e, const Integer &r, const Integer &s) const
544  {
545  const Integer &q = params.GetSubgroupOrder();
546  if (r>=q || r<1 || s>=q)
547  return false;
548 
549  // check r == (m_g^s * m_y^r + m) mod m_q
550  return r == (params.ConvertElementToInteger(publicKey.CascadeExponentiateBaseAndPublicElement(s, r)) + e) % q;
551  }
552 };
553 
554 /// \brief Discrete Log (DL) public key in GF(p) groups
555 /// \tparam GP GroupParameters derived class
556 /// \details DSA public key format is defined in 7.3.3 of RFC 2459. The private key format is defined in 12.9 of PKCS #11 v2.10.
557 template <class GP>
559 {
560 public:
561  virtual ~DL_PublicKey_GFP() {}
562 
563  /// \brief Initialize a public key over GF(p)
564  /// \param params the group parameters
565  /// \param y the public element
566  void Initialize(const DL_GroupParameters_IntegerBased &params, const Integer &y)
567  {this->AccessGroupParameters().Initialize(params); this->SetPublicElement(y);}
568 
569  /// \brief Initialize a public key over GF(p)
570  /// \param p the modulus
571  /// \param g the generator
572  /// \param y the public element
573  void Initialize(const Integer &p, const Integer &g, const Integer &y)
574  {this->AccessGroupParameters().Initialize(p, g); this->SetPublicElement(y);}
575 
576  /// \brief Initialize a public key over GF(p)
577  /// \param p the modulus
578  /// \param q the subgroup order
579  /// \param g the generator
580  /// \param y the public element
581  void Initialize(const Integer &p, const Integer &q, const Integer &g, const Integer &y)
582  {this->AccessGroupParameters().Initialize(p, q, g); this->SetPublicElement(y);}
583 
584  // X509PublicKey
586  {this->SetPublicElement(Integer(bt));}
588  {this->GetPublicElement().DEREncode(bt);}
589 };
590 
591 /// \brief Discrete Log (DL) private key in GF(p) groups
592 /// \tparam GP GroupParameters derived class
593 template <class GP>
595 {
596 public:
597  virtual ~DL_PrivateKey_GFP();
598 
599  /// \brief Create a private key
600  /// \param rng a RandomNumberGenerator derived class
601  /// \param modulusBits the size of the modulus, in bits
602  /// \details This function overload of Initialize() creates a new private key because it
603  /// takes a RandomNumberGenerator() as a parameter. If you have an existing keypair,
604  /// then use one of the other Initialize() overloads.
605  void Initialize(RandomNumberGenerator &rng, unsigned int modulusBits)
606  {this->GenerateRandomWithKeySize(rng, modulusBits);}
607 
608  /// \brief Create a private key
609  /// \param rng a RandomNumberGenerator derived class
610  /// \param p the modulus
611  /// \param g the generator
612  /// \details This function overload of Initialize() creates a new private key because it
613  /// takes a RandomNumberGenerator() as a parameter. If you have an existing keypair,
614  /// then use one of the other Initialize() overloads.
615  void Initialize(RandomNumberGenerator &rng, const Integer &p, const Integer &g)
616  {this->GenerateRandom(rng, MakeParameters("Modulus", p)("SubgroupGenerator", g));}
617 
618  /// \brief Create a private key
619  /// \param rng a RandomNumberGenerator derived class
620  /// \param p the modulus
621  /// \param q the subgroup order
622  /// \param g the generator
623  /// \details This function overload of Initialize() creates a new private key because it
624  /// takes a RandomNumberGenerator() as a parameter. If you have an existing keypair,
625  /// then use one of the other Initialize() overloads.
626  void Initialize(RandomNumberGenerator &rng, const Integer &p, const Integer &q, const Integer &g)
627  {this->GenerateRandom(rng, MakeParameters("Modulus", p)("SubgroupOrder", q)("SubgroupGenerator", g));}
628 
629  /// \brief Initialize a private key over GF(p)
630  /// \param params the group parameters
631  /// \param x the private exponent
632  void Initialize(const DL_GroupParameters_IntegerBased &params, const Integer &x)
633  {this->AccessGroupParameters().Initialize(params); this->SetPrivateExponent(x);}
634 
635  /// \brief Initialize a private key over GF(p)
636  /// \param p the modulus
637  /// \param g the generator
638  /// \param x the private exponent
639  void Initialize(const Integer &p, const Integer &g, const Integer &x)
640  {this->AccessGroupParameters().Initialize(p, g); this->SetPrivateExponent(x);}
641 
642  /// \brief Initialize a private key over GF(p)
643  /// \param p the modulus
644  /// \param q the subgroup order
645  /// \param g the generator
646  /// \param x the private exponent
647  void Initialize(const Integer &p, const Integer &q, const Integer &g, const Integer &x)
648  {this->AccessGroupParameters().Initialize(p, q, g); this->SetPrivateExponent(x);}
649 };
650 
651 // Out-of-line dtor due to AIX and GCC, http://github.com/weidai11/cryptopp/issues/499
652 template <class GP>
654 
655 /// \brief Discrete Log (DL) signing/verification keys in GF(p) groups
657 {
661 };
662 
663 /// \brief Discrete Log (DL) encryption/decryption keys in GF(p) groups
665 {
669 };
670 
671 /// \brief DSA signature scheme
672 /// \tparam H HashTransformation derived class
673 /// \sa <a href="http://www.weidai.com/scan-mirror/sig.html#DSA-1363">DSA-1363</a>
674 /// \since Crypto++ 1.0 for DSA, Crypto++ 5.6.2 for DSA2
675 template <class H>
676 struct GDSA : public DL_SS<
677  DL_SignatureKeys_GFP,
678  DL_Algorithm_GDSA<Integer>,
679  DL_SignatureMessageEncodingMethod_DSA,
680  H>
681 {
682 };
683 
684 /// \brief NR signature scheme
685 /// \tparam H HashTransformation derived class
686 /// \sa <a href="http://www.weidai.com/scan-mirror/sig.html#NR">NR</a>
687 template <class H>
688 struct NR : public DL_SS<
689  DL_SignatureKeys_GFP,
690  DL_Algorithm_NR<Integer>,
691  DL_SignatureMessageEncodingMethod_NR,
692  H>
693 {
694 };
695 
696 /// \brief DSA group parameters
697 /// \details These are GF(p) group parameters that are allowed by the DSA standard
698 /// \sa DL_Keys_DSA
699 /// \since Crypto++ 1.0
701 {
702 public:
703  virtual ~DL_GroupParameters_DSA() {}
704 
705  /// \brief Check the group for errors
706  /// \param rng RandomNumberGenerator for objects which use randomized testing
707  /// \param level level of thoroughness
708  /// \return true if the tests succeed, false otherwise
709  /// \details ValidateGroup() also checks that the lengths of p and q are allowed
710  /// by the DSA standard.
711  /// \details There are four levels of thoroughness:
712  /// <ul>
713  /// <li>0 - using this object won't cause a crash or exception
714  /// <li>1 - this object will probably function, and encrypt, sign, other operations correctly
715  /// <li>2 - ensure this object will function correctly, and perform reasonable security checks
716  /// <li>3 - perform reasonable security checks, and do checks that may take a long time
717  /// </ul>
718  /// \details Level 0 does not require a RandomNumberGenerator. A NullRNG() can be used for level 0.
719  /// Level 1 may not check for weak keys and such. Levels 2 and 3 are recommended.
720  bool ValidateGroup(RandomNumberGenerator &rng, unsigned int level) const;
721 
722  /// \brief Generate a random key or crypto parameters
723  /// \param rng a RandomNumberGenerator to produce keying material
724  /// \param alg additional initialization parameters
725  /// \details NameValuePairs can be ModulusSize alone; or Modulus, SubgroupOrder, and
726  /// SubgroupGenerator. ModulusSize must be between <tt>DSA::MIN_PRIME_LENGTH</tt> and
727  /// <tt>DSA::MAX_PRIME_LENGTH</tt>, and divisible by <tt>DSA::PRIME_LENGTH_MULTIPLE</tt>.
728  /// \details An example of changing the modulus size using NameValuePairs is shown below.
729  /// <pre>
730  /// AlgorithmParameters params = MakeParameters
731  /// (Name::ModulusSize(), 2048);
732  ///
733  /// DL_GroupParameters_DSA groupParams;
734  /// groupParams.GenerateRandom(prng, params);
735  /// </pre>
736  /// \throw KeyingErr if a key can't be generated or algorithm parameters are invalid.
737  void GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &alg);
738 
739  /// \brief Check the prime length for errors
740  /// \param pbits number of bits in the prime number
741  /// \return true if the tests succeed, false otherwise
742  static bool CRYPTOPP_API IsValidPrimeLength(unsigned int pbits)
743  {return pbits >= MIN_PRIME_LENGTH && pbits <= MAX_PRIME_LENGTH && pbits % PRIME_LENGTH_MULTIPLE == 0;}
744 
745  /// \brief DSA prime length
746  enum {
747  /// \brief Minimum prime length
748  MIN_PRIME_LENGTH = 1024,
749  /// \brief Maximum prime length
750  MAX_PRIME_LENGTH = 3072,
751  /// \brief Prime length multiple
752  PRIME_LENGTH_MULTIPLE = 1024
753  };
754 };
755 
756 template <class H>
757 class DSA2;
758 
759 /// \brief DSA keys
760 /// \sa DL_GroupParameters_DSA
761 /// \since Crypto++ 1.0
763 {
766 };
767 
768 /// \brief DSA signature scheme
769 /// \tparam H HashTransformation derived class
770 /// \details The class is named DSA2 instead of DSA for backwards compatibility because
771 /// DSA was a non-template class.
772 /// \details DSA default method GenerateRandom uses a 2048-bit modulus and a 224-bit subgoup by default.
773 /// The modulus can be changed using the following code:
774 /// <pre>
775 /// DSA::PrivateKey privateKey;
776 /// privateKey.GenerateRandomWithKeySize(prng, 2048);
777 /// </pre>
778 /// \details The subgroup order can be changed using the following code:
779 /// <pre>
780 /// AlgorithmParameters params = MakeParameters
781 /// (Name::ModulusSize(), 2048)
782 /// (Name::SubgroupOrderSize(), 256);
783 ///
784 /// DSA::PrivateKey privateKey;
785 /// privateKey.GenerateRandom(prng, params);
786 /// </pre>
787 /// \sa <a href="http://en.wikipedia.org/wiki/Digital_Signature_Algorithm">DSA</a>, as specified in FIPS 186-3,
788 /// <a href="https://www.cryptopp.com/wiki/Digital_Signature_Algorithm">Digital Signature Algorithm</a> on the wiki, and
789 /// <a href="https://www.cryptopp.com/wiki/NameValuePairs">NameValuePairs</a> on the wiki.
790 /// \since Crypto++ 1.0 for DSA, Crypto++ 5.6.2 for DSA2, Crypto++ 6.1 for 2048-bit modulus.
791 template <class H>
792 class DSA2 : public DL_SS<
793  DL_Keys_DSA,
794  DL_Algorithm_GDSA<Integer>,
795  DL_SignatureMessageEncodingMethod_DSA,
796  H,
797  DSA2<H> >
798 {
799 public:
800  static std::string CRYPTOPP_API StaticAlgorithmName() {return "DSA/" + (std::string)H::StaticAlgorithmName();}
801 };
802 
803 /// \brief DSA deterministic signature scheme
804 /// \tparam H HashTransformation derived class
805 /// \sa <a href="http://www.weidai.com/scan-mirror/sig.html#DSA-1363">DSA-1363</a>
806 /// \since Crypto++ 1.0 for DSA, Crypto++ 5.6.2 for DSA2
807 template <class H>
808 struct DSA_RFC6979 : public DL_SS<
809  DL_SignatureKeys_GFP,
810  DL_Algorithm_DSA_RFC6979<Integer, H>,
811  DL_SignatureMessageEncodingMethod_DSA,
812  H,
813  DSA_RFC6979<H> >
814 {
815  static std::string CRYPTOPP_API StaticAlgorithmName() {return std::string("DSA-RFC6979/") + H::StaticAlgorithmName();}
816 };
817 
818 /// DSA with SHA-1, typedef'd for backwards compatibility
819 typedef DSA2<SHA1> DSA;
820 
824 
825 /// \brief P1363 based XOR Encryption Method
826 /// \tparam MAC MessageAuthenticationCode derived class used for MAC computation
827 /// \tparam DHAES_MODE flag indicating DHAES mode
828 /// \tparam LABEL_OCTETS flag indicating the label is octet count
829 /// \details DL_EncryptionAlgorithm_Xor is based on an early P1363 draft, which itself appears to be based on an
830 /// early Certicom SEC-1 draft (or an early SEC-1 draft was based on a P1363 draft). Crypto++ 4.2 used it in its Integrated
831 /// Ecryption Schemes with <tt>NoCofactorMultiplication</tt>, <tt>DHAES_MODE=false</tt> and <tt>LABEL_OCTETS=true</tt>.
832 /// \details If you need this method for Crypto++ 4.2 compatibility, then use the ECIES template class with
833 /// <tt>NoCofactorMultiplication</tt>, <tt>DHAES_MODE=false</tt> and <tt>LABEL_OCTETS=true</tt>.
834 /// \details If you need this method for Bouncy Castle 1.54 and Botan 1.11 compatibility, then use the ECIES template class with
835 /// <tt>NoCofactorMultiplication</tt>, <tt>DHAES_MODE=ture</tt> and <tt>LABEL_OCTETS=false</tt>.
836 /// \details Bouncy Castle 1.54 and Botan 1.11 compatibility are the default template parameters.
837 /// \since Crypto++ 4.0
838 template <class MAC, bool DHAES_MODE, bool LABEL_OCTETS=false>
840 {
841 public:
842  virtual ~DL_EncryptionAlgorithm_Xor() {}
843 
844  bool ParameterSupported(const char *name) const {return strcmp(name, Name::EncodingParameters()) == 0;}
845  size_t GetSymmetricKeyLength(size_t plaintextLength) const
846  {return plaintextLength + static_cast<size_t>(MAC::DEFAULT_KEYLENGTH);}
847  size_t GetSymmetricCiphertextLength(size_t plaintextLength) const
848  {return plaintextLength + static_cast<size_t>(MAC::DIGESTSIZE);}
849  size_t GetMaxSymmetricPlaintextLength(size_t ciphertextLength) const
850  {return SaturatingSubtract(ciphertextLength, static_cast<size_t>(MAC::DIGESTSIZE));}
851  void SymmetricEncrypt(RandomNumberGenerator &rng, const byte *key, const byte *plaintext, size_t plaintextLength, byte *ciphertext, const NameValuePairs &parameters) const
852  {
853  CRYPTOPP_UNUSED(rng);
854  const byte *cipherKey = NULLPTR, *macKey = NULLPTR;
855  if (DHAES_MODE)
856  {
857  macKey = key;
858  cipherKey = key + MAC::DEFAULT_KEYLENGTH;
859  }
860  else
861  {
862  cipherKey = key;
863  macKey = key + plaintextLength;
864  }
865 
866  ConstByteArrayParameter encodingParameters;
867  parameters.GetValue(Name::EncodingParameters(), encodingParameters);
868 
869  if (plaintextLength) // Coverity finding
870  xorbuf(ciphertext, plaintext, cipherKey, plaintextLength);
871 
872  MAC mac(macKey);
873  mac.Update(ciphertext, plaintextLength);
874  mac.Update(encodingParameters.begin(), encodingParameters.size());
875  if (DHAES_MODE)
876  {
877  byte L[8];
878  PutWord(false, BIG_ENDIAN_ORDER, L, (LABEL_OCTETS ? word64(encodingParameters.size()) : 8 * word64(encodingParameters.size())));
879  mac.Update(L, 8);
880  }
881  mac.Final(ciphertext + plaintextLength);
882  }
883  DecodingResult SymmetricDecrypt(const byte *key, const byte *ciphertext, size_t ciphertextLength, byte *plaintext, const NameValuePairs &parameters) const
884  {
885  size_t plaintextLength = GetMaxSymmetricPlaintextLength(ciphertextLength);
886  const byte *cipherKey, *macKey;
887  if (DHAES_MODE)
888  {
889  macKey = key;
890  cipherKey = key + MAC::DEFAULT_KEYLENGTH;
891  }
892  else
893  {
894  cipherKey = key;
895  macKey = key + plaintextLength;
896  }
897 
898  ConstByteArrayParameter encodingParameters;
899  parameters.GetValue(Name::EncodingParameters(), encodingParameters);
900 
901  MAC mac(macKey);
902  mac.Update(ciphertext, plaintextLength);
903  mac.Update(encodingParameters.begin(), encodingParameters.size());
904  if (DHAES_MODE)
905  {
906  byte L[8];
907  PutWord(false, BIG_ENDIAN_ORDER, L, (LABEL_OCTETS ? word64(encodingParameters.size()) : 8 * word64(encodingParameters.size())));
908  mac.Update(L, 8);
909  }
910  if (!mac.Verify(ciphertext + plaintextLength))
911  return DecodingResult();
912 
913  if (plaintextLength) // Coverity finding
914  xorbuf(plaintext, ciphertext, cipherKey, plaintextLength);
915 
916  return DecodingResult(plaintextLength);
917  }
918 };
919 
920 /// \brief P1363 based Key Derivation Method
921 /// \tparam T FieldElement type or class
922 /// \tparam DHAES_MODE flag indicating DHAES mode
923 /// \tparam KDF key derivation function
924 /// \details FieldElement <tt>T</tt> can be Integer, ECP or EC2N.
925 template <class T, bool DHAES_MODE, class KDF>
927 {
928 public:
929  virtual ~DL_KeyDerivationAlgorithm_P1363() {}
930 
931  bool ParameterSupported(const char *name) const {return strcmp(name, Name::KeyDerivationParameters()) == 0;}
932  void Derive(const DL_GroupParameters<T> &params, byte *derivedKey, size_t derivedLength, const T &agreedElement, const T &ephemeralPublicKey, const NameValuePairs &parameters) const
933  {
934  SecByteBlock agreedSecret;
935  if (DHAES_MODE)
936  {
937  agreedSecret.New(params.GetEncodedElementSize(true) + params.GetEncodedElementSize(false));
938  params.EncodeElement(true, ephemeralPublicKey, agreedSecret);
939  params.EncodeElement(false, agreedElement, agreedSecret + params.GetEncodedElementSize(true));
940  }
941  else
942  {
943  agreedSecret.New(params.GetEncodedElementSize(false));
944  params.EncodeElement(false, agreedElement, agreedSecret);
945  }
946 
947  ConstByteArrayParameter derivationParameters;
948  parameters.GetValue(Name::KeyDerivationParameters(), derivationParameters);
949  KDF::DeriveKey(derivedKey, derivedLength, agreedSecret, agreedSecret.size(), derivationParameters.begin(), derivationParameters.size());
950  }
951 };
952 
953 /// \brief Discrete Log Integrated Encryption Scheme
954 /// \tparam COFACTOR_OPTION cofactor multiplication option
955 /// \tparam HASH HashTransformation derived class used for key drivation and MAC computation
956 /// \tparam DHAES_MODE flag indicating if the MAC includes addition context parameters such as the label
957 /// \tparam LABEL_OCTETS flag indicating if the label size is specified in octets or bits
958 /// \details DLIES is an Integer based Integrated Encryption Scheme (IES). The scheme combines a Key Encapsulation Method (KEM)
959 /// with a Data Encapsulation Method (DEM) and a MAC tag. The scheme is
960 /// <A HREF="http://en.wikipedia.org/wiki/ciphertext_indistinguishability">IND-CCA2</A>, which is a strong notion of security.
961 /// You should prefer an Integrated Encryption Scheme over homegrown schemes.
962 /// \details The library's original implementation is based on an early P1363 draft, which itself appears to be based on an early Certicom
963 /// SEC-1 draft (or an early SEC-1 draft was based on a P1363 draft). Crypto++ 4.2 used the early draft in its Integrated Ecryption
964 /// Schemes with <tt>NoCofactorMultiplication</tt>, <tt>DHAES_MODE=false</tt> and <tt>LABEL_OCTETS=true</tt>.
965 /// \details If you desire an Integrated Encryption Scheme with Crypto++ 4.2 compatibility, then use the DLIES template class with
966 /// <tt>NoCofactorMultiplication</tt>, <tt>DHAES_MODE=false</tt> and <tt>LABEL_OCTETS=true</tt>.
967 /// \details If you desire an Integrated Encryption Scheme with Bouncy Castle 1.54 and Botan 1.11 compatibility, then use the DLIES
968 /// template class with <tt>NoCofactorMultiplication</tt>, <tt>DHAES_MODE=true</tt> and <tt>LABEL_OCTETS=false</tt>.
969 /// \details The default template parameters ensure compatibility with Bouncy Castle 1.54 and Botan 1.11. The combination of
970 /// <tt>IncompatibleCofactorMultiplication</tt> and <tt>DHAES_MODE=true</tt> is recommended for best efficiency and security.
971 /// SHA1 is used for compatibility reasons, but it can be changed if desired. SHA-256 or another hash will likely improve the
972 /// security provided by the MAC. The hash is also used in the key derivation function as a PRF.
973 /// \details Below is an example of constructing a Crypto++ 4.2 compatible DLIES encryptor and decryptor.
974 /// <pre>
975 /// AutoSeededRandomPool prng;
976 /// DL_PrivateKey_GFP<DL_GroupParameters_GFP> key;
977 /// key.Initialize(prng, 2048);
978 ///
979 /// DLIES<SHA1,NoCofactorMultiplication,true,true>::Decryptor decryptor(key);
980 /// DLIES<SHA1,NoCofactorMultiplication,true,true>::Encryptor encryptor(decryptor);
981 /// </pre>
982 /// \sa ECIES, <a href="http://www.weidai.com/scan-mirror/ca.html#DLIES">Discrete Log Integrated Encryption Scheme (DLIES)</a>,
983 /// Martínez, Encinas, and Ávila's <A HREF="http://digital.csic.es/bitstream/10261/32671/1/V2-I2-P7-13.pdf">A Survey of the Elliptic
984 /// Curve Integrated Encryption Schemes</A>
985 /// \since Crypto++ 4.0, Crypto++ 5.7 for Bouncy Castle and Botan compatibility
986 template <class HASH = SHA1, class COFACTOR_OPTION = NoCofactorMultiplication, bool DHAES_MODE = true, bool LABEL_OCTETS=false>
987 struct DLIES
988  : public DL_ES<
989  DL_CryptoKeys_GFP,
990  DL_KeyAgreementAlgorithm_DH<Integer, COFACTOR_OPTION>,
991  DL_KeyDerivationAlgorithm_P1363<Integer, DHAES_MODE, P1363_KDF2<HASH> >,
992  DL_EncryptionAlgorithm_Xor<HMAC<HASH>, DHAES_MODE, LABEL_OCTETS>,
993  DLIES<> >
994 {
995  static std::string CRYPTOPP_API StaticAlgorithmName() {return "DLIES";} // TODO: fix this after name is standardized
996 };
997 
998 NAMESPACE_END
999 
1000 #if CRYPTOPP_MSC_VERSION
1001 # pragma warning(pop)
1002 #endif
1003 
1004 #endif
DL_GroupParameters_IntegerBasedImpl::SetModulusAndSubgroupGenerator
void SetModulusAndSubgroupGenerator(const Integer &p, const Integer &g)
Set group parameters.
Definition: gfpcrypt.h:211
SimpleKeyingInterface::SetKey
virtual void SetKey(const byte *key, size_t length, const NameValuePairs &params=g_nullNameValuePairs)
Sets or reset the key of this object.
DL_Algorithm_GDSA_ISO15946::Verify
bool Verify(const DL_GroupParameters< T > &params, const DL_PublicKey< T > &publicKey, const Integer &e, const Integer &r, const Integer &s) const
Verify a message using a public key.
Definition: gfpcrypt.h:503
DL_PrivateKeyImpl::SetPrivateExponent
void SetPrivateExponent(const Integer &x)
Sets the private exponent.
Definition: pubkey.h:1301
DL_Keys_DSA
DSA keys.
Definition: gfpcrypt.h:762
SecBlock::begin
iterator begin()
Provides an iterator pointing to the first element in the memory block.
Definition: secblock.h:836
Integer::InverseMod
Integer InverseMod(const Integer &n) const
Calculate multiplicative inverse.
ConstByteArrayParameter::size
size_t size() const
Length of the memory block.
Definition: algparam.h:88
EnumToType
Converts an enumeration to a type suitable for use as a template parameter.
Definition: cryptlib.h:135
MakeParameters
AlgorithmParameters MakeParameters(const char *name, const T &value, bool throwIfNotUsed=true)
Create an object that implements NameValuePairs.
Definition: algparam.h:508
DL_GroupParameters_IntegerBasedImpl::AccessBasePrecomputation
DL_FixedBasePrecomputation< Element > & AccessBasePrecomputation()
Retrieves the group precomputation.
Definition: gfpcrypt.h:200
HMAC_Base::Update
void Update(const byte *input, size_t length)
Updates a hash with additional input.
DL_PrivateKeyImpl
Discrete Log (DL) private key base implementation.
Definition: pubkey.h:1238
DL_PrivateKey_WithSignaturePairwiseConsistencyTest
Definition: pubkey.h:1314
DSA2
DSA signature scheme.
Definition: gfpcrypt.h:757
DL_PrivateKey_GFP::Initialize
void Initialize(RandomNumberGenerator &rng, unsigned int modulusBits)
Create a private key.
Definition: gfpcrypt.h:605
DL_GroupParameters_IntegerBased::GenerateRandom
void GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &alg)
Generate a random key.
DL_PublicKey_GFP
Discrete Log (DL) public key in GF(p) groups.
Definition: gfpcrypt.h:558
DL_ES
Discrete Log (DL) encryption scheme.
Definition: pubkey.h:2361
BIG_ENDIAN_ORDER
@ BIG_ENDIAN_ORDER
byte order is big-endian
Definition: cryptlib.h:147
DL_EncryptionAlgorithm_Xor
P1363 based XOR Encryption Method.
Definition: gfpcrypt.h:839
DL_PrivateKey_GFP::Initialize
void Initialize(RandomNumberGenerator &rng, const Integer &p, const Integer &q, const Integer &g)
Create a private key.
Definition: gfpcrypt.h:626
DL_GroupParameters_IntegerBasedImpl::GetGenerator
const Integer & GetGenerator() const
Retrieves a reference to the group generator.
Definition: gfpcrypt.h:209
GDSA
DSA signature scheme.
Definition: gfpcrypt.h:676
DL_GroupParameters_IntegerBased::Initialize
void Initialize(RandomNumberGenerator &rng, unsigned int pbits)
Create a group parameters over integers.
Definition: gfpcrypt.h:52
DL_SS
Discrete Log (DL) signature scheme.
Definition: pubkey.h:2338
DSA_RFC6979
DSA deterministic signature scheme.
Definition: gfpcrypt.h:808
ASN1CryptoMaterial
Encode and decode ASN.1 objects with additional information.
Definition: asn.h:683
DL_GroupParameters_IntegerBasedImpl::GetModulus
const Integer & GetModulus() const
Retrieve the modulus for the group.
Definition: gfpcrypt.h:205
Integer::MinEncodedSize
size_t MinEncodedSize(Signedness sign=UNSIGNED) const
Minimum number of bytes to encode this integer.
DL_GroupParameters_IntegerBased::ValidateGroup
bool ValidateGroup(RandomNumberGenerator &rng, unsigned int level) const
Check the group for errors.
DL_GroupParameters_IntegerBasedImpl::AssignFrom
void AssignFrom(const NameValuePairs &source)
Initialize or reinitialize this key.
Definition: gfpcrypt.h:195
DL_PublicKey_GFP::BERDecodePublicKey
void BERDecodePublicKey(BufferedTransformation &bt, bool, size_t)
Decode subjectPublicKey part of subjectPublicKeyInfo.
Definition: gfpcrypt.h:585
BufferedTransformation
Interface for buffered transformations.
Definition: cryptlib.h:1651
DL_FixedBasePrecomputation< Integer >
SecByteBlock
SecBlock<byte> typedef.
Definition: secblock.h:1226
DL_Algorithm_GDSA::Verify
bool Verify(const DL_GroupParameters< T > &params, const DL_PublicKey< T > &publicKey, const Integer &e, const Integer &r, const Integer &s) const
Verify a message using a public key.
Definition: gfpcrypt.h:305
CRYPTOPP_ASSERT
#define CRYPTOPP_ASSERT(exp)
Debugging and diagnostic assertion.
Definition: trap.h:68
DL_Algorithm_NR::Sign
void Sign(const DL_GroupParameters< T > &params, const Integer &x, const Integer &k, const Integer &e, Integer &r, Integer &s) const
Sign a message using a private key.
Definition: gfpcrypt.h:535
DL_PublicKey_GFP::Initialize
void Initialize(const Integer &p, const Integer &q, const Integer &g, const Integer &y)
Initialize a public key over GF(p)
Definition: gfpcrypt.h:581
DL_GroupParameters::ExponentiateBase
virtual Element ExponentiateBase(const Integer &exponent) const
Exponentiates the base.
Definition: pubkey.h:869
DL_GroupParameters_IntegerBased::FastSubgroupCheckAvailable
bool FastSubgroupCheckAvailable() const
Determine if subgroup membership check is fast.
Definition: gfpcrypt.h:105
DL_GroupParameters::ConvertElementToInteger
virtual Integer ConvertElementToInteger(const Element &element) const =0
Converts an element to an Integer.
smartptr.h
Classes for automatic resource management.
DL_Algorithm_GDSA::Sign
void Sign(const DL_GroupParameters< T > &params, const Integer &x, const Integer &k, const Integer &e, Integer &r, Integer &s) const
Sign a message using a private key.
Definition: gfpcrypt.h:296
pubkey.h
This file contains helper classes/functions for implementing public key algorithms.
DL_GroupParameters_IntegerBased::Initialize
void Initialize(const Integer &p, const Integer &g)
Initialize a group parameters over integers.
Definition: gfpcrypt.h:58
HMAC_Base::TruncatedFinal
void TruncatedFinal(byte *mac, size_t size)
Computes the hash of the current message.
DL_Algorithm_GDSA
GDSA algorithm.
Definition: gfpcrypt.h:289
DL_PublicKey< GP::Element >::SetPublicElement
virtual void SetPublicElement(const Element &y)
Sets the public element.
Definition: pubkey.h:1093
word64
unsigned long long word64
64-bit unsigned datatype
Definition: config_int.h:91
DL_GroupParameters_IntegerBased::SetSubgroupOrder
void SetSubgroupOrder(const Integer &q)
Set subgroup order.
Definition: gfpcrypt.h:161
DL_GroupParameters_GFP
GF(p) group parameters.
Definition: gfpcrypt.h:224
DL_GroupParametersImpl::GetGroupPrecomputation
const DL_GroupPrecomputation< Element > & GetGroupPrecomputation() const
Retrieves the group precomputation.
Definition: pubkey.h:1024
OID
Object Identifier.
Definition: asn.h:264
RandomNumberGenerator
Interface for random number generators.
Definition: cryptlib.h:1434
DL_PrivateKey_GFP
Discrete Log (DL) private key in GF(p) groups.
Definition: gfpcrypt.h:594
DL_CryptoKeys_GFP
Discrete Log (DL) encryption/decryption keys in GF(p) groups.
Definition: gfpcrypt.h:664
DL_GroupParameters_DSA
DSA group parameters.
Definition: gfpcrypt.h:700
DL_SymmetricEncryptionAlgorithm
Interface for symmetric encryption algorithms used in DL cryptosystems.
Definition: pubkey.h:1504
BitsToBytes
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:938
DL_GroupParameters_IntegerBased::GetModulus
virtual const Integer & GetModulus() const =0
Retrieve the modulus for the group.
DL_Algorithm_DSA_RFC6979
DSA signature algorithm based on RFC 6979.
Definition: gfpcrypt.h:327
operator==
bool operator==(const OID &lhs, const OID &rhs)
Compare two OIDs for equality.
misc.h
Utility functions for the Crypto++ library.
sha.h
Classes for SHA-1 and SHA-2 family of message digests.
ASN1Object::BERDecode
virtual void BERDecode(BufferedTransformation &bt)=0
Decode this object from a BufferedTransformation.
DL_PublicKey_GFP::DEREncodePublicKey
void DEREncodePublicKey(BufferedTransformation &bt) const
Encode subjectPublicKey part of subjectPublicKeyInfo.
Definition: gfpcrypt.h:587
STDMIN
const T & STDMIN(const T &a, const T &b)
Replacement function for std::min.
Definition: misc.h:655
DL_Algorithm_GDSA_ISO15946::Sign
void Sign(const DL_GroupParameters< T > &params, const Integer &x, const Integer &k, const Integer &e, Integer &r, Integer &s) const
Sign a message using a private key.
Definition: gfpcrypt.h:493
DL_PublicKey_GFP::Initialize
void Initialize(const Integer &p, const Integer &g, const Integer &y)
Initialize a public key over GF(p)
Definition: gfpcrypt.h:573
DL_PrivateKey_GFP::Initialize
void Initialize(RandomNumberGenerator &rng, const Integer &p, const Integer &g)
Create a private key.
Definition: gfpcrypt.h:615
DL_Algorithm_NR
NR algorithm.
Definition: gfpcrypt.h:528
DL_Algorithm_DSA_RFC6979::GenerateRandom
Integer GenerateRandom(const Integer &x, const Integer &q, const Integer &e) const
Generate k.
Definition: gfpcrypt.h:340
DL_ElgamalLikeSignatureAlgorithm
Interface for Elgamal-like signature algorithms.
Definition: pubkey.h:1406
DL_KeyDerivationAlgorithm
Interface for key derivation algorithms used in DL cryptosystems.
Definition: pubkey.h:1492
STDMAX
const T & STDMAX(const T &a, const T &b)
Replacement function for std::max.
Definition: misc.h:666
DL_GroupParameters_DSA::IsValidPrimeLength
static bool IsValidPrimeLength(unsigned int pbits)
Check the prime length for errors.
Definition: gfpcrypt.h:742
DL_PublicKey_GFP::Initialize
void Initialize(const DL_GroupParameters_IntegerBased &params, const Integer &y)
Initialize a public key over GF(p)
Definition: gfpcrypt.h:566
DL_GroupParameters_IntegerBased::Initialize
void Initialize(const DL_GroupParameters_IntegerBased &params)
Initialize a group parameters over integers.
Definition: gfpcrypt.h:43
DecodingResult
Returns a decoding results.
Definition: cryptlib.h:277
DL_GroupParameters< Integer >::SimultaneousExponentiate
virtual void SimultaneousExponentiate(Element *results, const Element &base, const Integer *exponents, unsigned int exponentsCount) const=0
Exponentiates a base to multiple exponents.
HMAC< H >
DL_GroupParameters_GFP::IsIdentity
bool IsIdentity(const Integer &element) const
Determines if an element is an identity.
Definition: gfpcrypt.h:235
NR
NR signature scheme.
Definition: gfpcrypt.h:688
asn.h
Classes and functions for working with ANS.1 objects.
DLIES
Discrete Log Integrated Encryption Scheme.
Definition: gfpcrypt.h:987
SecBlock::New
void New(size_type newSize)
Change size without preserving contents.
Definition: secblock.h:1126
DL_PrivateKey_GFP::Initialize
void Initialize(const Integer &p, const Integer &q, const Integer &g, const Integer &x)
Initialize a private key over GF(p)
Definition: gfpcrypt.h:647
DL_PublicKey::CascadeExponentiateBaseAndPublicElement
virtual Element CascadeExponentiateBaseAndPublicElement(const Integer &baseExp, const Integer &publicExp) const
Exponentiates an element.
Definition: pubkey.h:1110
DL_GroupParameters_IntegerBased::Initialize
void Initialize(const Integer &p, const Integer &q, const Integer &g)
Initialize a group parameters over integers.
Definition: gfpcrypt.h:65
DL_GroupParametersImpl::GetBasePrecomputation
const DL_FixedBasePrecomputation< Element > & GetBasePrecomputation() const
Retrieves the group precomputation.
Definition: pubkey.h:1028
DL_GroupParameters::GetSubgroupGenerator
virtual const Element & GetSubgroupGenerator() const
Retrieves the subgroup generator.
Definition: pubkey.h:859
Integer::BitCount
unsigned int BitCount() const
Determines the number of bits required to represent the Integer.
SecBlock::size
size_type size() const
Provides the count of elements in the SecBlock.
Definition: secblock.h:867
DL_KeyDerivationAlgorithm_P1363
P1363 based Key Derivation Method.
Definition: gfpcrypt.h:926
GeneratableCryptoMaterial::GenerateRandomWithKeySize
void GenerateRandomWithKeySize(RandomNumberGenerator &rng, unsigned int keySize)
Generate a random key or crypto parameters.
DL_GroupParameters_IntegerBasedImpl::GetVoidValue
bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
Get a named value.
Definition: gfpcrypt.h:192
ConstByteArrayParameter::begin
const byte * begin() const
Pointer to the first byte in the memory block.
Definition: algparam.h:84
Integer::Encode
void Encode(byte *output, size_t outputLen, Signedness sign=UNSIGNED) const
Encode in big-endian format.
CryptoPP
Crypto++ library namespace.
NameValuePairs::GetValue
bool GetValue(const char *name, T &value) const
Get a named value.
Definition: cryptlib.h:379
CRYPTOPP_API
#define CRYPTOPP_API
Win32 calling convention.
Definition: config_dll.h:119
CRYPTOPP_DLL_TEMPLATE_CLASS
#define CRYPTOPP_DLL_TEMPLATE_CLASS
Instantiate templates in a dynamic library.
Definition: config_dll.h:72
DeterministicSignatureAlgorithm
Interface for deterministic signers.
Definition: pubkey.h:1459
DL_PrivateKeyImpl::GenerateRandom
void GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &params)
Generate a random key or crypto parameters.
Definition: pubkey.h:1276
Integer::IsNegative
bool IsNegative() const
Determines if the Integer is negative.
Definition: integer.h:339
config.h
Library configuration file.
xorbuf
CRYPTOPP_DLL void xorbuf(byte *buf, const byte *mask, size_t count)
Performs an XOR of a buffer with a mask.
DL_PublicKey
Interface for Discrete Log (DL) public keys.
Definition: pubkey.h:1058
DL_GroupParameters_GFP::GetVoidValue
bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
Get a named value.
Definition: gfpcrypt.h:260
SaturatingSubtract
T1 SaturatingSubtract(const T1 &a, const T2 &b)
Performs a saturating subtract clamped at 0.
Definition: misc.h:1093
DL_GroupParameters< typename GROUP_PRECOMP::Element >::GetSubgroupOrder
virtual const Integer & GetSubgroupOrder() const=0
Retrieves the subgroup order.
DL_Algorithm_DSA_RFC6979::IsDeterministic
bool IsDeterministic() const
Signature scheme flag.
Definition: gfpcrypt.h:336
DL_Algorithm_GDSA_ISO15946
German Digital Signature Algorithm.
Definition: gfpcrypt.h:486
DL_GroupParameters< Integer >
operator!=
bool operator!=(const OID &lhs, const OID &rhs)
Compare two OIDs for inequality.
DL_PrivateKey_GFP::Initialize
void Initialize(const DL_GroupParameters_IntegerBased &params, const Integer &x)
Initialize a private key over GF(p)
Definition: gfpcrypt.h:632
DL_PublicKey< GP::Element >::GetPublicElement
virtual const Element & GetPublicElement() const
Retrieves the public element.
Definition: pubkey.h:1089
PutWord
void PutWord(bool assumeAligned, ByteOrder order, byte *block, T value, const byte *xorBlock=NULL)
Access a block of memory.
Definition: misc.h:2502
DSA
DSA2< SHA1 > DSA
DSA with SHA-1, typedef'd for backwards compatibility.
Definition: gfpcrypt.h:819
ASN1Object::DEREncode
virtual void DEREncode(BufferedTransformation &bt) const =0
Encode this object into a BufferedTransformation.
DL_GroupParameters_IntegerBasedImpl
Integer-based GroupParameters default implementation.
Definition: gfpcrypt.h:182
memcpy_s
void memcpy_s(void *dest, size_t sizeInBytes, const void *src, size_t count)
Bounds checking replacement for memcpy()
Definition: misc.h:525
DL_GroupParameters_GFP_DefaultSafePrime
GF(p) group parameters that default to safe primes.
Definition: gfpcrypt.h:274
DL_GroupParametersImpl
Base implementation of Discrete Log (DL) group parameters.
Definition: pubkey.h:1013
Integer::One
static const Integer & One()
Integer representing 1.
DL_GroupParameters::EncodeElement
virtual void EncodeElement(bool reversible, const Element &element, byte *encoded) const =0
Encodes the element.
DL_GroupParameters::GetEncodedElementSize
virtual unsigned int GetEncodedElementSize(bool reversible) const =0
Retrieves the encoded element's size.
NameValuePairs
Interface for retrieving values given their names.
Definition: cryptlib.h:321
DL_PrivateKey_GFP::Initialize
void Initialize(const Integer &p, const Integer &g, const Integer &x)
Initialize a private key over GF(p)
Definition: gfpcrypt.h:639
cryptlib.h
Abstract base classes that provide a uniform interface to this library.
ConstByteArrayParameter
Used to pass byte array input as part of a NameValuePairs object.
Definition: algparam.h:24
algparam.h
Classes for working with NameValuePairs.
integer.h
Multiple precision integer with arithmetic operations.
DL_GroupParameters_IntegerBased
Integer-based GroupParameters specialization.
Definition: gfpcrypt.h:34
DL_GroupParameters_IntegerBased::ConvertElementToInteger
Integer ConvertElementToInteger(const Element &element) const
Converts an element to an Integer.
Definition: gfpcrypt.h:139
hmac.h
Classes for HMAC message authentication codes.
Integer
Multiple precision integer with arithmetic operations.
Definition: integer.h:49
DL_Algorithm_NR::Verify
bool Verify(const DL_GroupParameters< T > &params, const DL_PublicKey< T > &publicKey, const Integer &e, const Integer &r, const Integer &s) const
Verify a message using a public key.
Definition: gfpcrypt.h:543
DL_PublicKeyImpl
Discrete Log (DL) public key base implementation.
Definition: pubkey.h:1335
DL_SignatureKeys_GFP
Discrete Log (DL) signing/verification keys in GF(p) groups.
Definition: gfpcrypt.h:656