eccrypto.h 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  1. // eccrypto.h - originally written and placed in the public domain by Wei Dai
  2. // deterministic signatures added by by Douglas Roark
  3. /// \file eccrypto.h
  4. /// \brief Classes and functions for Elliptic Curves over prime and binary fields
  5. #ifndef CRYPTOPP_ECCRYPTO_H
  6. #define CRYPTOPP_ECCRYPTO_H
  7. #include "config.h"
  8. #include "cryptlib.h"
  9. #include "pubkey.h"
  10. #include "integer.h"
  11. #include "asn.h"
  12. #include "hmac.h"
  13. #include "sha.h"
  14. #include "gfpcrypt.h"
  15. #include "dh.h"
  16. #include "mqv.h"
  17. #include "hmqv.h"
  18. #include "fhmqv.h"
  19. #include "ecp.h"
  20. #include "ec2n.h"
  21. #include <iosfwd>
  22. #if CRYPTOPP_MSC_VERSION
  23. # pragma warning(push)
  24. # pragma warning(disable: 4231 4275)
  25. #endif
  26. NAMESPACE_BEGIN(CryptoPP)
  27. /// \brief Elliptic Curve Parameters
  28. /// \tparam EC elliptic curve field
  29. /// \details This class corresponds to the ASN.1 sequence of the same name
  30. /// in ANSI X9.62 and SEC 1. EC is currently defined for ECP and EC2N.
  31. template <class EC>
  32. class DL_GroupParameters_EC : public DL_GroupParametersImpl<EcPrecomputation<EC> >
  33. {
  34. typedef DL_GroupParameters_EC<EC> ThisClass;
  35. public:
  36. typedef EC EllipticCurve;
  37. typedef typename EllipticCurve::Point Point;
  38. typedef Point Element;
  39. typedef IncompatibleCofactorMultiplication DefaultCofactorOption;
  40. virtual ~DL_GroupParameters_EC() {}
  41. /// \brief Construct an EC GroupParameters
  42. DL_GroupParameters_EC() : m_compress(false), m_encodeAsOID(true) {}
  43. /// \brief Construct an EC GroupParameters
  44. /// \param oid the OID of a curve
  45. DL_GroupParameters_EC(const OID &oid)
  46. : m_compress(false), m_encodeAsOID(true) {Initialize(oid);}
  47. /// \brief Construct an EC GroupParameters
  48. /// \param ec the elliptic curve
  49. /// \param G the base point
  50. /// \param n the order of the base point
  51. /// \param k the cofactor
  52. DL_GroupParameters_EC(const EllipticCurve &ec, const Point &G, const Integer &n, const Integer &k = Integer::Zero())
  53. : m_compress(false), m_encodeAsOID(true) {Initialize(ec, G, n, k);}
  54. /// \brief Construct an EC GroupParameters
  55. /// \param bt BufferedTransformation with group parameters
  56. DL_GroupParameters_EC(BufferedTransformation &bt)
  57. : m_compress(false), m_encodeAsOID(true) {BERDecode(bt);}
  58. /// \brief Initialize an EC GroupParameters using {EC,G,n,k}
  59. /// \param ec the elliptic curve
  60. /// \param G the base point
  61. /// \param n the order of the base point
  62. /// \param k the cofactor
  63. /// \details This Initialize() function overload initializes group parameters from existing parameters.
  64. void Initialize(const EllipticCurve &ec, const Point &G, const Integer &n, const Integer &k = Integer::Zero())
  65. {
  66. this->m_groupPrecomputation.SetCurve(ec);
  67. this->SetSubgroupGenerator(G);
  68. m_n = n;
  69. m_k = k;
  70. }
  71. /// \brief Initialize a DL_GroupParameters_EC {EC,G,n,k}
  72. /// \param oid the OID of a curve
  73. /// \details This Initialize() function overload initializes group parameters from existing parameters.
  74. void Initialize(const OID &oid);
  75. // NameValuePairs
  76. bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const;
  77. void AssignFrom(const NameValuePairs &source);
  78. // GeneratibleCryptoMaterial interface
  79. /// this implementation doesn't actually generate a curve, it just initializes the parameters with existing values
  80. /*! parameters: (Curve, SubgroupGenerator, SubgroupOrder, Cofactor (optional)), or (GroupOID) */
  81. void GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &alg);
  82. // DL_GroupParameters
  83. const DL_FixedBasePrecomputation<Element> & GetBasePrecomputation() const {return this->m_gpc;}
  84. DL_FixedBasePrecomputation<Element> & AccessBasePrecomputation() {return this->m_gpc;}
  85. const Integer & GetSubgroupOrder() const {return m_n;}
  86. Integer GetCofactor() const;
  87. bool ValidateGroup(RandomNumberGenerator &rng, unsigned int level) const;
  88. bool ValidateElement(unsigned int level, const Element &element, const DL_FixedBasePrecomputation<Element> *precomp) const;
  89. bool FastSubgroupCheckAvailable() const {return false;}
  90. void EncodeElement(bool reversible, const Element &element, byte *encoded) const
  91. {
  92. if (reversible)
  93. GetCurve().EncodePoint(encoded, element, m_compress);
  94. else
  95. element.x.Encode(encoded, GetEncodedElementSize(false));
  96. }
  97. virtual unsigned int GetEncodedElementSize(bool reversible) const
  98. {
  99. if (reversible)
  100. return GetCurve().EncodedPointSize(m_compress);
  101. else
  102. return GetCurve().GetField().MaxElementByteLength();
  103. }
  104. Element DecodeElement(const byte *encoded, bool checkForGroupMembership) const
  105. {
  106. Point result;
  107. if (!GetCurve().DecodePoint(result, encoded, GetEncodedElementSize(true)))
  108. throw DL_BadElement();
  109. if (checkForGroupMembership && !ValidateElement(1, result, NULLPTR))
  110. throw DL_BadElement();
  111. return result;
  112. }
  113. Integer ConvertElementToInteger(const Element &element) const;
  114. Integer GetMaxExponent() const {return GetSubgroupOrder()-1;}
  115. bool IsIdentity(const Element &element) const {return element.identity;}
  116. void SimultaneousExponentiate(Element *results, const Element &base, const Integer *exponents, unsigned int exponentsCount) const;
  117. static std::string CRYPTOPP_API StaticAlgorithmNamePrefix() {return "EC";}
  118. // ASN1Key
  119. OID GetAlgorithmID() const;
  120. // used by MQV
  121. Element MultiplyElements(const Element &a, const Element &b) const;
  122. Element CascadeExponentiate(const Element &element1, const Integer &exponent1, const Element &element2, const Integer &exponent2) const;
  123. // non-inherited
  124. // enumerate OIDs for recommended parameters, use OID() to get first one
  125. static OID CRYPTOPP_API GetNextRecommendedParametersOID(const OID &oid);
  126. void BERDecode(BufferedTransformation &bt);
  127. void DEREncode(BufferedTransformation &bt) const;
  128. void SetPointCompression(bool compress) {m_compress = compress;}
  129. bool GetPointCompression() const {return m_compress;}
  130. void SetEncodeAsOID(bool encodeAsOID) {m_encodeAsOID = encodeAsOID;}
  131. bool GetEncodeAsOID() const {return m_encodeAsOID;}
  132. const EllipticCurve& GetCurve() const {return this->m_groupPrecomputation.GetCurve();}
  133. bool operator==(const ThisClass &rhs) const
  134. {return this->m_groupPrecomputation.GetCurve() == rhs.m_groupPrecomputation.GetCurve() && this->m_gpc.GetBase(this->m_groupPrecomputation) == rhs.m_gpc.GetBase(rhs.m_groupPrecomputation);}
  135. protected:
  136. unsigned int FieldElementLength() const {return GetCurve().GetField().MaxElementByteLength();}
  137. unsigned int ExponentLength() const {return m_n.ByteCount();}
  138. OID m_oid; // set if parameters loaded from a recommended curve
  139. Integer m_n; // order of base point
  140. mutable Integer m_k; // cofactor
  141. mutable bool m_compress, m_encodeAsOID; // presentation details
  142. };
  143. inline std::ostream& operator<<(std::ostream& os, const DL_GroupParameters_EC<ECP>::Element& obj);
  144. /// \brief Elliptic Curve Discrete Log (DL) public key
  145. /// \tparam EC elliptic curve field
  146. template <class EC>
  147. class DL_PublicKey_EC : public DL_PublicKeyImpl<DL_GroupParameters_EC<EC> >
  148. {
  149. public:
  150. typedef typename EC::Point Element;
  151. virtual ~DL_PublicKey_EC() {}
  152. /// \brief Initialize an EC Public Key using {GP,Q}
  153. /// \param params group parameters
  154. /// \param Q the public point
  155. /// \details This Initialize() function overload initializes a public key from existing parameters.
  156. void Initialize(const DL_GroupParameters_EC<EC> &params, const Element &Q)
  157. {this->AccessGroupParameters() = params; this->SetPublicElement(Q);}
  158. /// \brief Initialize an EC Public Key using {EC,G,n,Q}
  159. /// \param ec the elliptic curve
  160. /// \param G the base point
  161. /// \param n the order of the base point
  162. /// \param Q the public point
  163. /// \details This Initialize() function overload initializes a public key from existing parameters.
  164. void Initialize(const EC &ec, const Element &G, const Integer &n, const Element &Q)
  165. {this->AccessGroupParameters().Initialize(ec, G, n); this->SetPublicElement(Q);}
  166. // X509PublicKey
  167. void BERDecodePublicKey(BufferedTransformation &bt, bool parametersPresent, size_t size);
  168. void DEREncodePublicKey(BufferedTransformation &bt) const;
  169. };
  170. /// \brief Elliptic Curve Discrete Log (DL) private key
  171. /// \tparam EC elliptic curve field
  172. template <class EC>
  173. class DL_PrivateKey_EC : public DL_PrivateKeyImpl<DL_GroupParameters_EC<EC> >
  174. {
  175. public:
  176. typedef typename EC::Point Element;
  177. virtual ~DL_PrivateKey_EC();
  178. /// \brief Initialize an EC Private Key using {GP,x}
  179. /// \param params group parameters
  180. /// \param x the private exponent
  181. /// \details This Initialize() function overload initializes a private key from existing parameters.
  182. void Initialize(const DL_GroupParameters_EC<EC> &params, const Integer &x)
  183. {this->AccessGroupParameters() = params; this->SetPrivateExponent(x);}
  184. /// \brief Initialize an EC Private Key using {EC,G,n,x}
  185. /// \param ec the elliptic curve
  186. /// \param G the base point
  187. /// \param n the order of the base point
  188. /// \param x the private exponent
  189. /// \details This Initialize() function overload initializes a private key from existing parameters.
  190. void Initialize(const EC &ec, const Element &G, const Integer &n, const Integer &x)
  191. {this->AccessGroupParameters().Initialize(ec, G, n); this->SetPrivateExponent(x);}
  192. /// \brief Create an EC private key
  193. /// \param rng a RandomNumberGenerator derived class
  194. /// \param params the EC group parameters
  195. /// \details This function overload of Initialize() creates a new private key because it
  196. /// takes a RandomNumberGenerator() as a parameter. If you have an existing keypair,
  197. /// then use one of the other Initialize() overloads.
  198. void Initialize(RandomNumberGenerator &rng, const DL_GroupParameters_EC<EC> &params)
  199. {this->GenerateRandom(rng, params);}
  200. /// \brief Create an EC private key
  201. /// \param rng a RandomNumberGenerator derived class
  202. /// \param ec the elliptic curve
  203. /// \param G the base point
  204. /// \param n the order of the base point
  205. /// \details This function overload of Initialize() creates a new private key because it
  206. /// takes a RandomNumberGenerator() as a parameter. If you have an existing keypair,
  207. /// then use one of the other Initialize() overloads.
  208. void Initialize(RandomNumberGenerator &rng, const EC &ec, const Element &G, const Integer &n)
  209. {this->GenerateRandom(rng, DL_GroupParameters_EC<EC>(ec, G, n));}
  210. // PKCS8PrivateKey
  211. void BERDecodePrivateKey(BufferedTransformation &bt, bool parametersPresent, size_t size);
  212. void DEREncodePrivateKey(BufferedTransformation &bt) const;
  213. };
  214. // Out-of-line dtor due to AIX and GCC, http://github.com/weidai11/cryptopp/issues/499
  215. template<class EC>
  216. DL_PrivateKey_EC<EC>::~DL_PrivateKey_EC() {}
  217. /// \brief Elliptic Curve Diffie-Hellman
  218. /// \tparam EC elliptic curve field
  219. /// \tparam COFACTOR_OPTION cofactor multiplication option
  220. /// \sa CofactorMultiplicationOption, <a href="http://www.weidai.com/scan-mirror/ka.html#ECDH">Elliptic Curve Diffie-Hellman, AKA ECDH</a>
  221. /// \since Crypto++ 3.0
  222. template <class EC, class COFACTOR_OPTION = typename DL_GroupParameters_EC<EC>::DefaultCofactorOption>
  223. struct ECDH
  224. {
  225. typedef DH_Domain<DL_GroupParameters_EC<EC>, COFACTOR_OPTION> Domain;
  226. };
  227. /// \brief Elliptic Curve Menezes-Qu-Vanstone
  228. /// \tparam EC elliptic curve field
  229. /// \tparam COFACTOR_OPTION cofactor multiplication option
  230. /// \sa CofactorMultiplicationOption, <a href="http://www.weidai.com/scan-mirror/ka.html#ECMQV">Elliptic Curve Menezes-Qu-Vanstone, AKA ECMQV</a>
  231. template <class EC, class COFACTOR_OPTION = typename DL_GroupParameters_EC<EC>::DefaultCofactorOption>
  232. struct ECMQV
  233. {
  234. typedef MQV_Domain<DL_GroupParameters_EC<EC>, COFACTOR_OPTION> Domain;
  235. };
  236. /// \brief Hashed Elliptic Curve Menezes-Qu-Vanstone
  237. /// \tparam EC elliptic curve field
  238. /// \tparam COFACTOR_OPTION cofactor multiplication option
  239. /// \details This implementation follows Hugo Krawczyk's <a href="http://eprint.iacr.org/2005/176">HMQV: A High-Performance
  240. /// Secure Diffie-Hellman Protocol</a>. Note: this implements HMQV only. HMQV-C with Key Confirmation is not provided.
  241. /// \sa CofactorMultiplicationOption
  242. template <class EC, class COFACTOR_OPTION = typename DL_GroupParameters_EC<EC>::DefaultCofactorOption, class HASH = SHA256>
  243. struct ECHMQV
  244. {
  245. typedef HMQV_Domain<DL_GroupParameters_EC<EC>, COFACTOR_OPTION, HASH> Domain;
  246. };
  247. typedef ECHMQV< ECP, DL_GroupParameters_EC< ECP >::DefaultCofactorOption, SHA1 >::Domain ECHMQV160;
  248. typedef ECHMQV< ECP, DL_GroupParameters_EC< ECP >::DefaultCofactorOption, SHA256 >::Domain ECHMQV256;
  249. typedef ECHMQV< ECP, DL_GroupParameters_EC< ECP >::DefaultCofactorOption, SHA384 >::Domain ECHMQV384;
  250. typedef ECHMQV< ECP, DL_GroupParameters_EC< ECP >::DefaultCofactorOption, SHA512 >::Domain ECHMQV512;
  251. /// \brief Fully Hashed Elliptic Curve Menezes-Qu-Vanstone
  252. /// \tparam EC elliptic curve field
  253. /// \tparam COFACTOR_OPTION cofactor multiplication option
  254. /// \details This implementation follows Augustin P. Sarr and Philippe Elbaz–Vincent, and Jean–Claude Bajard's
  255. /// <a href="http://eprint.iacr.org/2009/408">A Secure and Efficient Authenticated Diffie-Hellman Protocol</a>.
  256. /// Note: this is FHMQV, Protocol 5, from page 11; and not FHMQV-C.
  257. /// \sa CofactorMultiplicationOption
  258. template <class EC, class COFACTOR_OPTION = typename DL_GroupParameters_EC<EC>::DefaultCofactorOption, class HASH = SHA256>
  259. struct ECFHMQV
  260. {
  261. typedef FHMQV_Domain<DL_GroupParameters_EC<EC>, COFACTOR_OPTION, HASH> Domain;
  262. };
  263. typedef ECFHMQV< ECP, DL_GroupParameters_EC< ECP >::DefaultCofactorOption, SHA1 >::Domain ECFHMQV160;
  264. typedef ECFHMQV< ECP, DL_GroupParameters_EC< ECP >::DefaultCofactorOption, SHA256 >::Domain ECFHMQV256;
  265. typedef ECFHMQV< ECP, DL_GroupParameters_EC< ECP >::DefaultCofactorOption, SHA384 >::Domain ECFHMQV384;
  266. typedef ECFHMQV< ECP, DL_GroupParameters_EC< ECP >::DefaultCofactorOption, SHA512 >::Domain ECFHMQV512;
  267. /// \brief Elliptic Curve Discrete Log (DL) keys
  268. /// \tparam EC elliptic curve field
  269. template <class EC>
  270. struct DL_Keys_EC
  271. {
  272. typedef DL_PublicKey_EC<EC> PublicKey;
  273. typedef DL_PrivateKey_EC<EC> PrivateKey;
  274. };
  275. // Forward declaration; documented below
  276. template <class EC, class H>
  277. struct ECDSA;
  278. /// \brief Elliptic Curve DSA keys
  279. /// \tparam EC elliptic curve field
  280. /// \since Crypto++ 3.2
  281. template <class EC>
  282. struct DL_Keys_ECDSA
  283. {
  284. typedef DL_PublicKey_EC<EC> PublicKey;
  285. typedef DL_PrivateKey_WithSignaturePairwiseConsistencyTest<DL_PrivateKey_EC<EC>, ECDSA<EC, SHA256> > PrivateKey;
  286. };
  287. /// \brief Elliptic Curve DSA (ECDSA) signature algorithm
  288. /// \tparam EC elliptic curve field
  289. /// \since Crypto++ 3.2
  290. template <class EC>
  291. class DL_Algorithm_ECDSA : public DL_Algorithm_GDSA<typename EC::Point>
  292. {
  293. public:
  294. CRYPTOPP_STATIC_CONSTEXPR const char* CRYPTOPP_API StaticAlgorithmName() {return "ECDSA";}
  295. };
  296. /// \brief Elliptic Curve DSA (ECDSA) signature algorithm based on RFC 6979
  297. /// \tparam EC elliptic curve field
  298. /// \sa <a href="http://tools.ietf.org/rfc/rfc6979.txt">RFC 6979, Deterministic Usage of the
  299. /// Digital Signature Algorithm (DSA) and Elliptic Curve Digital Signature Algorithm (ECDSA)</a>
  300. /// \since Crypto++ 6.0
  301. template <class EC, class H>
  302. class DL_Algorithm_ECDSA_RFC6979 : public DL_Algorithm_DSA_RFC6979<typename EC::Point, H>
  303. {
  304. public:
  305. CRYPTOPP_STATIC_CONSTEXPR const char* CRYPTOPP_API StaticAlgorithmName() {return "ECDSA-RFC6979";}
  306. };
  307. /// \brief Elliptic Curve NR (ECNR) signature algorithm
  308. /// \tparam EC elliptic curve field
  309. template <class EC>
  310. class DL_Algorithm_ECNR : public DL_Algorithm_NR<typename EC::Point>
  311. {
  312. public:
  313. CRYPTOPP_STATIC_CONSTEXPR const char* CRYPTOPP_API StaticAlgorithmName() {return "ECNR";}
  314. };
  315. /// \brief Elliptic Curve DSA (ECDSA) signature scheme
  316. /// \tparam EC elliptic curve field
  317. /// \tparam H HashTransformation derived class
  318. /// \sa <a href="http://www.weidai.com/scan-mirror/sig.html#ECDSA">ECDSA</a>
  319. /// \since Crypto++ 3.2
  320. template <class EC, class H>
  321. struct ECDSA : public DL_SS<DL_Keys_ECDSA<EC>, DL_Algorithm_ECDSA<EC>, DL_SignatureMessageEncodingMethod_DSA, H>
  322. {
  323. };
  324. /// \brief Elliptic Curve DSA (ECDSA) deterministic signature scheme
  325. /// \tparam EC elliptic curve field
  326. /// \tparam H HashTransformation derived class
  327. /// \sa <a href="http://tools.ietf.org/rfc/rfc6979.txt">Deterministic Usage of the
  328. /// Digital Signature Algorithm (DSA) and Elliptic Curve Digital Signature Algorithm (ECDSA)</a>
  329. /// \since Crypto++ 6.0
  330. template <class EC, class H>
  331. struct ECDSA_RFC6979 : public DL_SS<
  332. DL_Keys_ECDSA<EC>,
  333. DL_Algorithm_ECDSA_RFC6979<EC, H>,
  334. DL_SignatureMessageEncodingMethod_DSA,
  335. H,
  336. ECDSA_RFC6979<EC,H> >
  337. {
  338. static std::string CRYPTOPP_API StaticAlgorithmName() {return std::string("ECDSA-RFC6979/") + H::StaticAlgorithmName();}
  339. };
  340. /// \brief Elliptic Curve NR (ECNR) signature scheme
  341. /// \tparam EC elliptic curve field
  342. /// \tparam H HashTransformation derived class
  343. template <class EC, class H = SHA1>
  344. struct ECNR : public DL_SS<DL_Keys_EC<EC>, DL_Algorithm_ECNR<EC>, DL_SignatureMessageEncodingMethod_NR, H>
  345. {
  346. };
  347. // ******************************************
  348. template <class EC>
  349. class DL_PublicKey_ECGDSA;
  350. template <class EC>
  351. class DL_PrivateKey_ECGDSA;
  352. /// \brief Elliptic Curve German DSA key for ISO/IEC 15946
  353. /// \tparam EC elliptic curve field
  354. /// \sa ECGDSA
  355. /// \since Crypto++ 6.0
  356. template <class EC>
  357. class DL_PrivateKey_ECGDSA : public DL_PrivateKeyImpl<DL_GroupParameters_EC<EC> >
  358. {
  359. public:
  360. typedef typename EC::Point Element;
  361. virtual ~DL_PrivateKey_ECGDSA() {}
  362. /// \brief Initialize an EC Private Key using {GP,x}
  363. /// \param params group parameters
  364. /// \param x the private exponent
  365. /// \details This Initialize() function overload initializes a private key from existing parameters.
  366. void Initialize(const DL_GroupParameters_EC<EC> &params, const Integer &x)
  367. {
  368. this->AccessGroupParameters() = params;
  369. this->SetPrivateExponent(x);
  370. CRYPTOPP_ASSERT(x>=1 && x<=params.GetSubgroupOrder()-1);
  371. }
  372. /// \brief Initialize an EC Private Key using {EC,G,n,x}
  373. /// \param ec the elliptic curve
  374. /// \param G the base point
  375. /// \param n the order of the base point
  376. /// \param x the private exponent
  377. /// \details This Initialize() function overload initializes a private key from existing parameters.
  378. void Initialize(const EC &ec, const Element &G, const Integer &n, const Integer &x)
  379. {
  380. this->AccessGroupParameters().Initialize(ec, G, n);
  381. this->SetPrivateExponent(x);
  382. CRYPTOPP_ASSERT(x>=1 && x<=this->AccessGroupParameters().GetSubgroupOrder()-1);
  383. }
  384. /// \brief Create an EC private key
  385. /// \param rng a RandomNumberGenerator derived class
  386. /// \param params the EC group parameters
  387. /// \details This function overload of Initialize() creates a new private key because it
  388. /// takes a RandomNumberGenerator() as a parameter. If you have an existing keypair,
  389. /// then use one of the other Initialize() overloads.
  390. void Initialize(RandomNumberGenerator &rng, const DL_GroupParameters_EC<EC> &params)
  391. {this->GenerateRandom(rng, params);}
  392. /// \brief Create an EC private key
  393. /// \param rng a RandomNumberGenerator derived class
  394. /// \param ec the elliptic curve
  395. /// \param G the base point
  396. /// \param n the order of the base point
  397. /// \details This function overload of Initialize() creates a new private key because it
  398. /// takes a RandomNumberGenerator() as a parameter. If you have an existing keypair,
  399. /// then use one of the other Initialize() overloads.
  400. void Initialize(RandomNumberGenerator &rng, const EC &ec, const Element &G, const Integer &n)
  401. {this->GenerateRandom(rng, DL_GroupParameters_EC<EC>(ec, G, n));}
  402. virtual void MakePublicKey(DL_PublicKey_ECGDSA<EC> &pub) const
  403. {
  404. const DL_GroupParameters<Element>& params = this->GetAbstractGroupParameters();
  405. pub.AccessAbstractGroupParameters().AssignFrom(params);
  406. const Integer &xInv = this->GetPrivateExponent().InverseMod(params.GetSubgroupOrder());
  407. pub.SetPublicElement(params.ExponentiateBase(xInv));
  408. CRYPTOPP_ASSERT(xInv.NotZero());
  409. }
  410. virtual bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
  411. {
  412. return GetValueHelper<DL_PrivateKey_ECGDSA<EC>,
  413. DL_PrivateKey_ECGDSA<EC> >(this, name, valueType, pValue).Assignable();
  414. }
  415. virtual void AssignFrom(const NameValuePairs &source)
  416. {
  417. AssignFromHelper<DL_PrivateKey_ECGDSA<EC>,
  418. DL_PrivateKey_ECGDSA<EC> >(this, source);
  419. }
  420. // PKCS8PrivateKey
  421. void BERDecodePrivateKey(BufferedTransformation &bt, bool parametersPresent, size_t size);
  422. void DEREncodePrivateKey(BufferedTransformation &bt) const;
  423. };
  424. /// \brief Elliptic Curve German DSA key for ISO/IEC 15946
  425. /// \tparam EC elliptic curve field
  426. /// \sa ECGDSA
  427. /// \since Crypto++ 6.0
  428. template <class EC>
  429. class DL_PublicKey_ECGDSA : public DL_PublicKeyImpl<DL_GroupParameters_EC<EC> >
  430. {
  431. typedef DL_PublicKey_ECGDSA<EC> ThisClass;
  432. public:
  433. typedef typename EC::Point Element;
  434. virtual ~DL_PublicKey_ECGDSA() {}
  435. /// \brief Initialize an EC Public Key using {GP,Q}
  436. /// \param params group parameters
  437. /// \param Q the public point
  438. /// \details This Initialize() function overload initializes a public key from existing parameters.
  439. void Initialize(const DL_GroupParameters_EC<EC> &params, const Element &Q)
  440. {this->AccessGroupParameters() = params; this->SetPublicElement(Q);}
  441. /// \brief Initialize an EC Public Key using {EC,G,n,Q}
  442. /// \param ec the elliptic curve
  443. /// \param G the base point
  444. /// \param n the order of the base point
  445. /// \param Q the public point
  446. /// \details This Initialize() function overload initializes a public key from existing parameters.
  447. void Initialize(const EC &ec, const Element &G, const Integer &n, const Element &Q)
  448. {this->AccessGroupParameters().Initialize(ec, G, n); this->SetPublicElement(Q);}
  449. virtual void AssignFrom(const NameValuePairs &source)
  450. {
  451. DL_PrivateKey_ECGDSA<EC> *pPrivateKey = NULLPTR;
  452. if (source.GetThisPointer(pPrivateKey))
  453. pPrivateKey->MakePublicKey(*this);
  454. else
  455. {
  456. this->AccessAbstractGroupParameters().AssignFrom(source);
  457. AssignFromHelper(this, source)
  458. CRYPTOPP_SET_FUNCTION_ENTRY(PublicElement);
  459. }
  460. }
  461. // DL_PublicKey<T>
  462. virtual void SetPublicElement(const Element &y)
  463. {this->AccessPublicPrecomputation().SetBase(this->GetAbstractGroupParameters().GetGroupPrecomputation(), y);}
  464. // X509PublicKey
  465. void BERDecodePublicKey(BufferedTransformation &bt, bool parametersPresent, size_t size);
  466. void DEREncodePublicKey(BufferedTransformation &bt) const;
  467. };
  468. /// \brief Elliptic Curve German DSA keys for ISO/IEC 15946
  469. /// \tparam EC elliptic curve field
  470. /// \sa ECGDSA
  471. /// \since Crypto++ 6.0
  472. template <class EC>
  473. struct DL_Keys_ECGDSA
  474. {
  475. typedef DL_PublicKey_ECGDSA<EC> PublicKey;
  476. typedef DL_PrivateKey_ECGDSA<EC> PrivateKey;
  477. };
  478. /// \brief Elliptic Curve German DSA signature algorithm
  479. /// \tparam EC elliptic curve field
  480. /// \sa ECGDSA
  481. /// \since Crypto++ 6.0
  482. template <class EC>
  483. class DL_Algorithm_ECGDSA : public DL_Algorithm_GDSA_ISO15946<typename EC::Point>
  484. {
  485. public:
  486. CRYPTOPP_STATIC_CONSTEXPR const char* CRYPTOPP_API StaticAlgorithmName() {return "ECGDSA";}
  487. };
  488. /// \brief Elliptic Curve German Digital Signature Algorithm signature scheme
  489. /// \tparam EC elliptic curve field
  490. /// \tparam H HashTransformation derived class
  491. /// \sa Erwin Hess, Marcus Schafheutle, and Pascale Serf <A
  492. /// HREF="http://www.teletrust.de/fileadmin/files/oid/ecgdsa_final.pdf">The Digital Signature Scheme
  493. /// ECGDSA (October 24, 2006)</A>
  494. /// \since Crypto++ 6.0
  495. template <class EC, class H>
  496. struct ECGDSA : public DL_SS<
  497. DL_Keys_ECGDSA<EC>,
  498. DL_Algorithm_ECGDSA<EC>,
  499. DL_SignatureMessageEncodingMethod_DSA,
  500. H>
  501. {
  502. static std::string CRYPTOPP_API StaticAlgorithmName() {return std::string("ECGDSA-ISO15946/") + H::StaticAlgorithmName();}
  503. };
  504. // ******************************************
  505. /// \brief Elliptic Curve Integrated Encryption Scheme
  506. /// \tparam COFACTOR_OPTION cofactor multiplication option
  507. /// \tparam HASH HashTransformation derived class used for key derivation and MAC computation
  508. /// \tparam DHAES_MODE flag indicating if the MAC includes additional context parameters such as <em>u·V</em>, <em>v·U</em> and label
  509. /// \tparam LABEL_OCTETS flag indicating if the label size is specified in octets or bits
  510. /// \details ECIES is an Elliptic Curve based Integrated Encryption Scheme (IES). The scheme combines a Key Encapsulation
  511. /// Method (KEM) with a Data Encapsulation Method (DEM) and a MAC tag. The scheme is
  512. /// <A HREF="http://en.wikipedia.org/wiki/ciphertext_indistinguishability">IND-CCA2</A>, which is a strong notion of security.
  513. /// You should prefer an Integrated Encryption Scheme over homegrown schemes.
  514. /// \details If you desire an Integrated Encryption Scheme with Crypto++ 4.2 compatibility, then use the ECIES_P1363.
  515. /// If you desire an Integrated Encryption Scheme compatible with Bouncy Castle 1.54 and Botan 1.11 compatibility, then use the ECIES
  516. /// template class with <tt>NoCofactorMultiplication</tt>, <tt>DHAES_MODE=true</tt> and <tt>LABEL_OCTETS=false</tt>.
  517. /// \details The default template parameters ensure compatibility with Bouncy Castle 1.54 and Botan 1.11. The combination of
  518. /// <tt>IncompatibleCofactorMultiplication</tt> and <tt>DHAES_MODE=true</tt> is recommended for best efficiency and security.
  519. /// SHA1 is used for compatibility reasons, but it can be changed if desired.
  520. /// \sa DLIES, ECIES_P1363, <a href="http://www.weidai.com/scan-mirror/ca.html#ECIES">Elliptic Curve Integrated Encryption Scheme (ECIES)</a>,
  521. /// 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
  522. /// Curve Integrated Encryption Schemes</A>
  523. /// \since Crypto++ 4.0, Crypto++ 5.7 for Bouncy Castle and Botan compatibility
  524. template <class EC, class HASH = SHA1, class COFACTOR_OPTION = NoCofactorMultiplication, bool DHAES_MODE = true, bool LABEL_OCTETS = false>
  525. struct ECIES
  526. : public DL_ES<
  527. DL_Keys_EC<EC>,
  528. DL_KeyAgreementAlgorithm_DH<typename EC::Point, COFACTOR_OPTION>,
  529. DL_KeyDerivationAlgorithm_P1363<typename EC::Point, DHAES_MODE, P1363_KDF2<HASH> >,
  530. DL_EncryptionAlgorithm_Xor<HMAC<HASH>, DHAES_MODE, LABEL_OCTETS>,
  531. ECIES<EC> >
  532. {
  533. // TODO: fix this after name is standardized
  534. CRYPTOPP_STATIC_CONSTEXPR const char* CRYPTOPP_API StaticAlgorithmName() {return "ECIES";}
  535. };
  536. /// \brief Elliptic Curve Integrated Encryption Scheme for P1363
  537. /// \tparam COFACTOR_OPTION cofactor multiplication option
  538. /// \tparam HASH HashTransformation derived class used for key derivation and MAC computation
  539. /// \details ECIES_P1363 is an Elliptic Curve based Integrated Encryption Scheme (IES) for P1363. The scheme combines a Key Encapsulation
  540. /// Method (KEM) with a Data Encapsulation Method (DEM) and a MAC tag. The scheme is
  541. /// <A HREF="http://en.wikipedia.org/wiki/ciphertext_indistinguishability">IND-CCA2</A>, which is a strong notion of security.
  542. /// You should prefer an Integrated Encryption Scheme over homegrown schemes.
  543. /// \details The library's original implementation is based on an early P1363 draft, which itself appears to be based on an early Certicom
  544. /// 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 Enryption
  545. /// Schemes with <tt>NoCofactorMultiplication</tt>, <tt>DHAES_MODE=false</tt> and <tt>LABEL_OCTETS=true</tt>.
  546. /// \details If you desire an Integrated Encryption Scheme with Crypto++ 4.2 compatibility, then use the ECIES_P1363.
  547. /// If you desire an Integrated Encryption Scheme compatible with Bouncy Castle 1.54 and Botan 1.11 compatibility, then use the ECIES
  548. /// template class with <tt>NoCofactorMultiplication</tt>, <tt>DHAES_MODE=true</tt> and <tt>LABEL_OCTETS=false</tt>.
  549. /// \details The default template parameters ensure compatibility with P1363. The combination of
  550. /// <tt>IncompatibleCofactorMultiplication</tt> and <tt>DHAES_MODE=true</tt> is recommended for best efficiency and security.
  551. /// SHA1 is used for compatibility reasons, but it can be changed if desired.
  552. /// \sa DLIES, ECIES, <a href="http://www.weidai.com/scan-mirror/ca.html#ECIES">Elliptic Curve Integrated Encryption Scheme (ECIES)</a>,
  553. /// 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
  554. /// Curve Integrated Encryption Schemes</A>
  555. /// \since Crypto++ 4.0
  556. template <class EC, class HASH = SHA1, class COFACTOR_OPTION = NoCofactorMultiplication>
  557. struct ECIES_P1363
  558. : public DL_ES<
  559. DL_Keys_EC<EC>,
  560. DL_KeyAgreementAlgorithm_DH<typename EC::Point, COFACTOR_OPTION>,
  561. DL_KeyDerivationAlgorithm_P1363<typename EC::Point, false, P1363_KDF2<HASH> >,
  562. DL_EncryptionAlgorithm_Xor<HMAC<HASH>, false, true>,
  563. ECIES<EC> >
  564. {
  565. // TODO: fix this after name is standardized
  566. CRYPTOPP_STATIC_CONSTEXPR const char* CRYPTOPP_API StaticAlgorithmName() {return "ECIES-P1363";}
  567. };
  568. NAMESPACE_END
  569. #ifdef CRYPTOPP_MANUALLY_INSTANTIATE_TEMPLATES
  570. #include "eccrypto.cpp"
  571. #endif
  572. NAMESPACE_BEGIN(CryptoPP)
  573. CRYPTOPP_DLL_TEMPLATE_CLASS DL_GroupParameters_EC<ECP>;
  574. CRYPTOPP_DLL_TEMPLATE_CLASS DL_GroupParameters_EC<EC2N>;
  575. CRYPTOPP_DLL_TEMPLATE_CLASS DL_PublicKeyImpl<DL_GroupParameters_EC<ECP> >;
  576. CRYPTOPP_DLL_TEMPLATE_CLASS DL_PublicKeyImpl<DL_GroupParameters_EC<EC2N> >;
  577. CRYPTOPP_DLL_TEMPLATE_CLASS DL_PublicKey_EC<ECP>;
  578. CRYPTOPP_DLL_TEMPLATE_CLASS DL_PublicKey_EC<EC2N>;
  579. CRYPTOPP_DLL_TEMPLATE_CLASS DL_PublicKey_ECGDSA<ECP>;
  580. CRYPTOPP_DLL_TEMPLATE_CLASS DL_PublicKey_ECGDSA<EC2N>;
  581. CRYPTOPP_DLL_TEMPLATE_CLASS DL_PrivateKeyImpl<DL_GroupParameters_EC<ECP> >;
  582. CRYPTOPP_DLL_TEMPLATE_CLASS DL_PrivateKeyImpl<DL_GroupParameters_EC<EC2N> >;
  583. CRYPTOPP_DLL_TEMPLATE_CLASS DL_PrivateKey_EC<ECP>;
  584. CRYPTOPP_DLL_TEMPLATE_CLASS DL_PrivateKey_EC<EC2N>;
  585. CRYPTOPP_DLL_TEMPLATE_CLASS DL_PrivateKey_ECGDSA<ECP>;
  586. CRYPTOPP_DLL_TEMPLATE_CLASS DL_PrivateKey_ECGDSA<EC2N>;
  587. CRYPTOPP_DLL_TEMPLATE_CLASS DL_Algorithm_GDSA<ECP::Point>;
  588. CRYPTOPP_DLL_TEMPLATE_CLASS DL_Algorithm_GDSA<EC2N::Point>;
  589. CRYPTOPP_DLL_TEMPLATE_CLASS DL_PrivateKey_WithSignaturePairwiseConsistencyTest<DL_PrivateKey_EC<ECP>, ECDSA<ECP, SHA256> >;
  590. CRYPTOPP_DLL_TEMPLATE_CLASS DL_PrivateKey_WithSignaturePairwiseConsistencyTest<DL_PrivateKey_EC<EC2N>, ECDSA<EC2N, SHA256> >;
  591. NAMESPACE_END
  592. #if CRYPTOPP_MSC_VERSION
  593. # pragma warning(pop)
  594. #endif
  595. #endif