xed25519.h 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825
  1. // xed25519.h - written and placed in public domain by Jeffrey Walton
  2. // Crypto++ specific implementation wrapped around Andrew
  3. // Moon's public domain curve25519-donna and ed25519-donna,
  4. // http://github.com/floodyberry/curve25519-donna and
  5. // http://github.com/floodyberry/ed25519-donna.
  6. // Typically the key agreement classes encapsulate their data more
  7. // than x25519 does below. They are a little more accessible
  8. // due to crypto_box operations.
  9. /// \file xed25519.h
  10. /// \brief Classes for x25519 and ed25519 operations
  11. /// \details This implementation integrates Andrew Moon's public domain code
  12. /// for curve25519-donna and ed25519-donna.
  13. /// \details Moving keys into and out of the library proceeds as follows.
  14. /// If an Integer class is accepted or returned, then the data is in big
  15. /// endian format. That is, the MSB is at byte position 0, and the LSB
  16. /// is at byte position 31. The Integer will work as expected, just like
  17. /// an int or a long.
  18. /// \details If a byte array is accepted, then the byte array is in little
  19. /// endian format. That is, the LSB is at byte position 0, and the MSB is
  20. /// at byte position 31. This follows the implementation where byte 0 is
  21. /// clamed with 248. That is my_arr[0] &= 248 to mask the lower 3 bits.
  22. /// \details PKCS8 and X509 keys encoded using ASN.1 follow little endian
  23. /// arrays. The format is specified in <A HREF=
  24. /// "http:///tools.ietf.org/html/draft-ietf-curdle-pkix">draft-ietf-curdle-pkix</A>.
  25. /// \details If you have a little endian array and you want to wrap it in
  26. /// an Integer using big endian then you can perform the following:
  27. /// <pre>Integer x(my_arr, SECRET_KEYLENGTH, UNSIGNED, LITTLE_ENDIAN_ORDER);</pre>
  28. /// \sa Andrew Moon's x22519 GitHub <A
  29. /// HREF="http://github.com/floodyberry/curve25519-donna">curve25519-donna</A>,
  30. /// ed22519 GitHub <A
  31. /// HREF="http://github.com/floodyberry/ed25519-donna">ed25519-donna</A>, and
  32. /// <A HREF="http:///tools.ietf.org/html/draft-ietf-curdle-pkix">draft-ietf-curdle-pkix</A>
  33. /// \since Crypto++ 8.0
  34. #ifndef CRYPTOPP_XED25519_H
  35. #define CRYPTOPP_XED25519_H
  36. #include "cryptlib.h"
  37. #include "pubkey.h"
  38. #include "oids.h"
  39. NAMESPACE_BEGIN(CryptoPP)
  40. class Integer;
  41. struct ed25519Signer;
  42. struct ed25519Verifier;
  43. // ******************** x25519 Agreement ************************* //
  44. /// \brief x25519 with key validation
  45. /// \since Crypto++ 8.0
  46. class x25519 : public SimpleKeyAgreementDomain, public CryptoParameters, public PKCS8PrivateKey
  47. {
  48. public:
  49. /// \brief Size of the private key
  50. /// \details SECRET_KEYLENGTH is the size of the private key, in bytes.
  51. CRYPTOPP_CONSTANT(SECRET_KEYLENGTH = 32);
  52. /// \brief Size of the public key
  53. /// \details PUBLIC_KEYLENGTH is the size of the public key, in bytes.
  54. CRYPTOPP_CONSTANT(PUBLIC_KEYLENGTH = 32);
  55. /// \brief Size of the shared key
  56. /// \details SHARED_KEYLENGTH is the size of the shared key, in bytes.
  57. CRYPTOPP_CONSTANT(SHARED_KEYLENGTH = 32);
  58. virtual ~x25519() {}
  59. /// \brief Create a x25519 object
  60. /// \details This constructor creates an empty x25519 object. It is
  61. /// intended for use in loading existing parameters, like CryptoBox
  62. /// parameters. If you are performing key agreement you should use a
  63. /// constructor that generates random parameters on construction.
  64. x25519() {}
  65. /// \brief Create a x25519 object
  66. /// \param y public key
  67. /// \param x private key
  68. /// \details This constructor creates a x25519 object using existing parameters.
  69. /// \note The public key is not validated.
  70. x25519(const byte y[PUBLIC_KEYLENGTH], const byte x[SECRET_KEYLENGTH]);
  71. /// \brief Create a x25519 object
  72. /// \param x private key
  73. /// \details This constructor creates a x25519 object using existing parameters.
  74. /// The public key is calculated from the private key.
  75. x25519(const byte x[SECRET_KEYLENGTH]);
  76. /// \brief Create a x25519 object
  77. /// \param y public key
  78. /// \param x private key
  79. /// \details This constructor creates a x25519 object using existing parameters.
  80. /// \note The public key is not validated.
  81. x25519(const Integer &y, const Integer &x);
  82. /// \brief Create a x25519 object
  83. /// \param x private key
  84. /// \details This constructor creates a x25519 object using existing parameters.
  85. /// The public key is calculated from the private key.
  86. x25519(const Integer &x);
  87. /// \brief Create a x25519 object
  88. /// \param rng RandomNumberGenerator derived class
  89. /// \details This constructor creates a new x25519 using the random number generator.
  90. x25519(RandomNumberGenerator &rng);
  91. /// \brief Create a x25519 object
  92. /// \param params public and private key
  93. /// \details This constructor creates a x25519 object using existing parameters.
  94. /// The <tt>params</tt> can be created with <tt>Save</tt>.
  95. /// \note The public key is not validated.
  96. x25519(BufferedTransformation &params);
  97. /// \brief Create a x25519 object
  98. /// \param oid an object identifier
  99. /// \details This constructor creates a new x25519 using the specified OID. The public
  100. /// and private points are uninitialized.
  101. x25519(const OID &oid);
  102. /// \brief Clamp a private key
  103. /// \param x private key
  104. /// \details ClampKeys() clamps a private key and then regenerates the
  105. /// public key from the private key.
  106. void ClampKey(byte x[SECRET_KEYLENGTH]) const;
  107. /// \brief Determine if private key is clamped
  108. /// \param x private key
  109. bool IsClamped(const byte x[SECRET_KEYLENGTH]) const;
  110. /// \brief Test if a key has small order
  111. /// \param y public key
  112. bool IsSmallOrder(const byte y[PUBLIC_KEYLENGTH]) const;
  113. /// \brief Get the Object Identifier
  114. /// \return the Object Identifier
  115. /// \details The default OID is from RFC 8410 using <tt>id-X25519</tt>.
  116. /// The default private key format is RFC 5208.
  117. OID GetAlgorithmID() const {
  118. return m_oid.Empty() ? ASN1::X25519() : m_oid;
  119. }
  120. /// \brief Set the Object Identifier
  121. /// \param oid the new Object Identifier
  122. void SetAlgorithmID(const OID& oid) {
  123. m_oid = oid;
  124. }
  125. // CryptoParameters
  126. bool Validate(RandomNumberGenerator &rng, unsigned int level) const;
  127. bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const;
  128. void AssignFrom(const NameValuePairs &source);
  129. // CryptoParameters
  130. CryptoParameters & AccessCryptoParameters() {return *this;}
  131. /// \brief DER encode ASN.1 object
  132. /// \param bt BufferedTransformation object
  133. /// \details Save() will write the OID associated with algorithm or scheme.
  134. /// In the case of public and private keys, this function writes the
  135. /// subjectPublicKeyInfo parts.
  136. /// \details The default OID is from RFC 8410 using <tt>id-X25519</tt>.
  137. /// The default private key format is RFC 5208, which is the old format.
  138. /// The old format provides the best interop, and keys will work
  139. /// with OpenSSL.
  140. /// \sa <A HREF="http://tools.ietf.org/rfc/rfc5958.txt">RFC 5958, Asymmetric
  141. /// Key Packages</A>
  142. void Save(BufferedTransformation &bt) const {
  143. DEREncode(bt, 0);
  144. }
  145. /// \brief DER encode ASN.1 object
  146. /// \param bt BufferedTransformation object
  147. /// \param v1 flag indicating v1
  148. /// \details Save() will write the OID associated with algorithm or scheme.
  149. /// In the case of public and private keys, this function writes the
  150. /// subjectPublicKeyInfo parts.
  151. /// \details The default OID is from RFC 8410 using <tt>id-X25519</tt>.
  152. /// The default private key format is RFC 5208.
  153. /// \details v1 means INTEGER 0 is written. INTEGER 0 means
  154. /// RFC 5208 format, which is the old format. The old format provides
  155. /// the best interop, and keys will work with OpenSSL. The other
  156. /// option uses INTEGER 1. INTEGER 1 means RFC 5958 format,
  157. /// which is the new format.
  158. /// \sa <A HREF="http://tools.ietf.org/rfc/rfc5958.txt">RFC 5958, Asymmetric
  159. /// Key Packages</A>
  160. void Save(BufferedTransformation &bt, bool v1) const {
  161. DEREncode(bt, v1 ? 0 : 1);
  162. }
  163. /// \brief BER decode ASN.1 object
  164. /// \param bt BufferedTransformation object
  165. /// \sa <A HREF="http://tools.ietf.org/rfc/rfc5958.txt">RFC 5958, Asymmetric
  166. /// Key Packages</A>
  167. void Load(BufferedTransformation &bt) {
  168. BERDecode(bt);
  169. }
  170. // PKCS8PrivateKey
  171. void BERDecode(BufferedTransformation &bt);
  172. void DEREncode(BufferedTransformation &bt) const { DEREncode(bt, 0); }
  173. void BERDecodePrivateKey(BufferedTransformation &bt, bool parametersPresent, size_t size);
  174. void DEREncodePrivateKey(BufferedTransformation &bt) const;
  175. /// \brief DER encode ASN.1 object
  176. /// \param bt BufferedTransformation object
  177. /// \param version indicates version
  178. /// \details DEREncode() will write the OID associated with algorithm or
  179. /// scheme. In the case of public and private keys, this function writes
  180. /// the subjectPublicKeyInfo parts.
  181. /// \details The default OID is from RFC 8410 using <tt>id-X25519</tt>.
  182. /// The default private key format is RFC 5208.
  183. /// \details The value of version is written as the INTEGER. INTEGER 0 means
  184. /// RFC 5208 format, which is the old format. The old format provides
  185. /// the best interop, and keys will work with OpenSSL. The INTEGER 1
  186. /// means RFC 5958 format, which is the new format.
  187. void DEREncode(BufferedTransformation &bt, int version) const;
  188. /// \brief Determine if OID is valid for this object
  189. /// \details BERDecodeAndCheckAlgorithmID() parses the OID from
  190. /// <tt>bt</tt> and determines if it valid for this object. The
  191. /// problem in practice is there are multiple OIDs available to
  192. /// denote curve25519 operations. The OIDs include an old GNU
  193. /// OID used by SSH, OIDs specified in draft-josefsson-pkix-newcurves,
  194. /// and OIDs specified in draft-ietf-curdle-pkix.
  195. /// \details By default BERDecodeAndCheckAlgorithmID() accepts an
  196. /// OID set by the user, <tt>ASN1::curve25519()</tt> and <tt>ASN1::X25519()</tt>.
  197. /// <tt>ASN1::curve25519()</tt> is generic and says "this key is valid for
  198. /// curve25519 operations". <tt>ASN1::X25519()</tt> is specific and says
  199. /// "this key is valid for x25519 key exchange."
  200. void BERDecodeAndCheckAlgorithmID(BufferedTransformation& bt);
  201. // DL_PrivateKey
  202. void GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &params);
  203. // SimpleKeyAgreementDomain
  204. unsigned int AgreedValueLength() const {return SHARED_KEYLENGTH;}
  205. unsigned int PrivateKeyLength() const {return SECRET_KEYLENGTH;}
  206. unsigned int PublicKeyLength() const {return PUBLIC_KEYLENGTH;}
  207. // SimpleKeyAgreementDomain
  208. void GeneratePrivateKey(RandomNumberGenerator &rng, byte *privateKey) const;
  209. void GeneratePublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const;
  210. bool Agree(byte *agreedValue, const byte *privateKey, const byte *otherPublicKey, bool validateOtherPublicKey=true) const;
  211. protected:
  212. // Create a public key from a private key
  213. void SecretToPublicKey(byte y[PUBLIC_KEYLENGTH], const byte x[SECRET_KEYLENGTH]) const;
  214. protected:
  215. FixedSizeSecBlock<byte, SECRET_KEYLENGTH> m_sk;
  216. FixedSizeSecBlock<byte, PUBLIC_KEYLENGTH> m_pk;
  217. OID m_oid; // preferred OID
  218. };
  219. // ****************** ed25519 Signer *********************** //
  220. /// \brief ed25519 message accumulator
  221. /// \details ed25519 buffers the entire message, and does not
  222. /// digest the message incrementally. You should be careful with
  223. /// large messages like files on-disk. The behavior is by design
  224. /// because Bernstein feels small messages should be authenticated;
  225. /// and larger messages will be digested by the application.
  226. /// \details The accumulator is used for signing and verification.
  227. /// The first 64-bytes of storage is reserved for the signature.
  228. /// During signing the signature storage is unused. During
  229. /// verification the first 64 bytes holds the signature. The
  230. /// signature is provided by the PK_Verifier framework and the
  231. /// call to PK_Signer::InputSignature. Member functions data()
  232. /// and size() refer to the accumulated message. Member function
  233. /// signature() refers to the signature with an implicit size of
  234. /// SIGNATURE_LENGTH bytes.
  235. /// \details Applications which digest large messages, like an ISO
  236. /// disk file, should take care because the design effectively
  237. /// disgorges the format operation from the signing operation.
  238. /// Put another way, be careful to ensure what you are signing is
  239. /// is in fact a digest of the intended message, and not a different
  240. /// message digest supplied by an attacker.
  241. struct ed25519_MessageAccumulator : public PK_MessageAccumulator
  242. {
  243. CRYPTOPP_CONSTANT(RESERVE_SIZE=2048+64);
  244. CRYPTOPP_CONSTANT(SIGNATURE_LENGTH=64);
  245. /// \brief Create a message accumulator
  246. ed25519_MessageAccumulator() {
  247. Restart();
  248. }
  249. /// \brief Create a message accumulator
  250. /// \details ed25519 does not use a RNG. You can safely use
  251. /// NullRNG() because IsProbablistic returns false.
  252. ed25519_MessageAccumulator(RandomNumberGenerator &rng) {
  253. CRYPTOPP_UNUSED(rng); Restart();
  254. }
  255. /// \brief Add data to the accumulator
  256. /// \param msg pointer to the data to accumulate
  257. /// \param len the size of the data, in bytes
  258. void Update(const byte* msg, size_t len) {
  259. if (msg && len)
  260. m_msg.insert(m_msg.end(), msg, msg+len);
  261. }
  262. /// \brief Reset the accumulator
  263. void Restart() {
  264. m_msg.reserve(RESERVE_SIZE);
  265. m_msg.resize(SIGNATURE_LENGTH);
  266. }
  267. /// \brief Retrieve pointer to signature buffer
  268. /// \return pointer to signature buffer
  269. byte* signature() {
  270. return &m_msg[0];
  271. }
  272. /// \brief Retrieve pointer to signature buffer
  273. /// \return pointer to signature buffer
  274. const byte* signature() const {
  275. return &m_msg[0];
  276. }
  277. /// \brief Retrieve pointer to data buffer
  278. /// \return pointer to data buffer
  279. const byte* data() const {
  280. return &m_msg[0]+SIGNATURE_LENGTH;
  281. }
  282. /// \brief Retrieve size of data buffer
  283. /// \return size of the data buffer, in bytes
  284. size_t size() const {
  285. return m_msg.size()-SIGNATURE_LENGTH;
  286. }
  287. protected:
  288. // TODO: Find an equivalent Crypto++ structure.
  289. std::vector<byte, AllocatorWithCleanup<byte> > m_msg;
  290. };
  291. /// \brief Ed25519 private key
  292. /// \details ed25519PrivateKey is somewhat of a hack. It needed to
  293. /// provide DL_PrivateKey interface to fit into the existing
  294. /// framework, but it lacks a lot of the internals of a true
  295. /// DL_PrivateKey. The missing pieces include GroupParameters
  296. /// and Point, which provide the low level field operations
  297. /// found in traditional implementations like NIST curves over
  298. /// prime and binary fields.
  299. /// \details ed25519PrivateKey is also unusual because the
  300. /// class members of interest are byte arrays and not Integers.
  301. /// In addition, the byte arrays are little-endian meaning
  302. /// LSB is at element 0 and the MSB is at element 31.
  303. /// If you call GetPrivateExponent() then the little-endian byte
  304. /// array is converted to a big-endian Integer() so it can be
  305. /// returned the way a caller expects. And calling
  306. /// SetPrivateExponent performs a similar internal conversion.
  307. /// \since Crypto++ 8.0
  308. struct ed25519PrivateKey : public PKCS8PrivateKey
  309. {
  310. /// \brief Size of the private key
  311. /// \details SECRET_KEYLENGTH is the size of the private key, in bytes.
  312. CRYPTOPP_CONSTANT(SECRET_KEYLENGTH = 32);
  313. /// \brief Size of the public key
  314. /// \details PUBLIC_KEYLENGTH is the size of the public key, in bytes.
  315. CRYPTOPP_CONSTANT(PUBLIC_KEYLENGTH = 32);
  316. /// \brief Size of the signature
  317. /// \details SIGNATURE_LENGTH is the size of the signature, in bytes.
  318. /// ed25519 is a DL-based signature scheme. The signature is the
  319. /// concatenation of <tt>r || s</tt>.
  320. CRYPTOPP_CONSTANT(SIGNATURE_LENGTH = 64);
  321. virtual ~ed25519PrivateKey() {}
  322. // CryptoMaterial
  323. bool Validate(RandomNumberGenerator &rng, unsigned int level) const;
  324. bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const;
  325. void AssignFrom(const NameValuePairs &source);
  326. // GroupParameters
  327. OID GetAlgorithmID() const {
  328. return m_oid.Empty() ? ASN1::Ed25519() : m_oid;
  329. }
  330. /// \brief DER encode ASN.1 object
  331. /// \param bt BufferedTransformation object
  332. /// \details Save() will write the OID associated with algorithm or scheme.
  333. /// In the case of public and private keys, this function writes the
  334. /// subjectPublicKeyInfo parts.
  335. /// \details The default OID is from RFC 8410 using <tt>id-Ed25519</tt>.
  336. /// The default private key format is RFC 5208, which is the old format.
  337. /// The old format provides the best interop, and keys will work
  338. /// with OpenSSL.
  339. /// \sa <A HREF="http://tools.ietf.org/rfc/rfc5958.txt">RFC 5958, Asymmetric
  340. /// Key Packages</A>
  341. void Save(BufferedTransformation &bt) const {
  342. DEREncode(bt, 0);
  343. }
  344. /// \brief DER encode ASN.1 object
  345. /// \param bt BufferedTransformation object
  346. /// \param v1 flag indicating v1
  347. /// \details Save() will write the OID associated with algorithm or scheme.
  348. /// In the case of public and private keys, this function writes the
  349. /// subjectPublicKeyInfo parts.
  350. /// \details The default OID is from RFC 8410 using <tt>id-Ed25519</tt>.
  351. /// The default private key format is RFC 5208.
  352. /// \details v1 means INTEGER 0 is written. INTEGER 0 means
  353. /// RFC 5208 format, which is the old format. The old format provides
  354. /// the best interop, and keys will work with OpenSSL. The other
  355. /// option uses INTEGER 1. INTEGER 1 means RFC 5958 format,
  356. /// which is the new format.
  357. /// \sa <A HREF="http://tools.ietf.org/rfc/rfc5958.txt">RFC 5958, Asymmetric
  358. /// Key Packages</A>
  359. void Save(BufferedTransformation &bt, bool v1) const {
  360. DEREncode(bt, v1 ? 0 : 1);
  361. }
  362. /// \brief BER decode ASN.1 object
  363. /// \param bt BufferedTransformation object
  364. /// \sa <A HREF="http://tools.ietf.org/rfc/rfc5958.txt">RFC 5958, Asymmetric
  365. /// Key Packages</A>
  366. void Load(BufferedTransformation &bt) {
  367. BERDecode(bt);
  368. }
  369. /// \brief Initializes a public key from this key
  370. /// \param pub reference to a public key
  371. void MakePublicKey(PublicKey &pub) const;
  372. // PKCS8PrivateKey
  373. void BERDecode(BufferedTransformation &bt);
  374. void DEREncode(BufferedTransformation &bt) const { DEREncode(bt, 0); }
  375. void BERDecodePrivateKey(BufferedTransformation &bt, bool parametersPresent, size_t size);
  376. void DEREncodePrivateKey(BufferedTransformation &bt) const;
  377. /// \brief DER encode ASN.1 object
  378. /// \param bt BufferedTransformation object
  379. /// \param version indicates version
  380. /// \details DEREncode() will write the OID associated with algorithm or
  381. /// scheme. In the case of public and private keys, this function writes
  382. /// the subjectPublicKeyInfo parts.
  383. /// \details The default OID is from RFC 8410 using <tt>id-X25519</tt>.
  384. /// The default private key format is RFC 5208.
  385. /// \details The value of version is written as the INTEGER. INTEGER 0 means
  386. /// RFC 5208 format, which is the old format. The old format provides
  387. /// the best interop, and keys will work with OpenSSL. The INTEGER 1
  388. /// means RFC 5958 format, which is the new format.
  389. void DEREncode(BufferedTransformation &bt, int version) const;
  390. /// \brief Determine if OID is valid for this object
  391. /// \details BERDecodeAndCheckAlgorithmID() parses the OID from
  392. /// <tt>bt</tt> and determines if it valid for this object. The
  393. /// problem in practice is there are multiple OIDs available to
  394. /// denote curve25519 operations. The OIDs include an old GNU
  395. /// OID used by SSH, OIDs specified in draft-josefsson-pkix-newcurves,
  396. /// and OIDs specified in draft-ietf-curdle-pkix.
  397. /// \details By default BERDecodeAndCheckAlgorithmID() accepts an
  398. /// OID set by the user, <tt>ASN1::curve25519()</tt> and <tt>ASN1::Ed25519()</tt>.
  399. /// <tt>ASN1::curve25519()</tt> is generic and says "this key is valid for
  400. /// curve25519 operations". <tt>ASN1::Ed25519()</tt> is specific and says
  401. /// "this key is valid for ed25519 signing."
  402. void BERDecodeAndCheckAlgorithmID(BufferedTransformation& bt);
  403. // PKCS8PrivateKey
  404. void GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &params);
  405. void SetPrivateExponent(const byte x[SECRET_KEYLENGTH]);
  406. void SetPrivateExponent(const Integer &x);
  407. const Integer& GetPrivateExponent() const;
  408. /// \brief Test if a key has small order
  409. /// \param y public key
  410. bool IsSmallOrder(const byte y[PUBLIC_KEYLENGTH]) const;
  411. /// \brief Retrieve private key byte array
  412. /// \return the private key byte array
  413. /// \details GetPrivateKeyBytePtr() is used by signing code to call ed25519_sign.
  414. const byte* GetPrivateKeyBytePtr() const {
  415. return m_sk.begin();
  416. }
  417. /// \brief Retrieve public key byte array
  418. /// \return the public key byte array
  419. /// \details GetPublicKeyBytePtr() is used by signing code to call ed25519_sign.
  420. const byte* GetPublicKeyBytePtr() const {
  421. return m_pk.begin();
  422. }
  423. protected:
  424. // Create a public key from a private key
  425. void SecretToPublicKey(byte y[PUBLIC_KEYLENGTH], const byte x[SECRET_KEYLENGTH]) const;
  426. protected:
  427. FixedSizeSecBlock<byte, SECRET_KEYLENGTH> m_sk;
  428. FixedSizeSecBlock<byte, PUBLIC_KEYLENGTH> m_pk;
  429. OID m_oid; // preferred OID
  430. mutable Integer m_x; // for DL_PrivateKey
  431. };
  432. /// \brief Ed25519 signature algorithm
  433. /// \since Crypto++ 8.0
  434. struct ed25519Signer : public PK_Signer
  435. {
  436. /// \brief Size of the private key
  437. /// \details SECRET_KEYLENGTH is the size of the private key, in bytes.
  438. CRYPTOPP_CONSTANT(SECRET_KEYLENGTH = 32);
  439. /// \brief Size of the public key
  440. /// \details PUBLIC_KEYLENGTH is the size of the public key, in bytes.
  441. CRYPTOPP_CONSTANT(PUBLIC_KEYLENGTH = 32);
  442. /// \brief Size of the signature
  443. /// \details SIGNATURE_LENGTH is the size of the signature, in bytes.
  444. /// ed25519 is a DL-based signature scheme. The signature is the
  445. /// concatenation of <tt>r || s</tt>.
  446. CRYPTOPP_CONSTANT(SIGNATURE_LENGTH = 64);
  447. typedef Integer Element;
  448. virtual ~ed25519Signer() {}
  449. /// \brief Create an ed25519Signer object
  450. ed25519Signer() {}
  451. /// \brief Create an ed25519Signer object
  452. /// \param y public key
  453. /// \param x private key
  454. /// \details This constructor creates an ed25519Signer object using existing parameters.
  455. /// \note The public key is not validated.
  456. ed25519Signer(const byte y[PUBLIC_KEYLENGTH], const byte x[SECRET_KEYLENGTH]);
  457. /// \brief Create an ed25519Signer object
  458. /// \param x private key
  459. /// \details This constructor creates an ed25519Signer object using existing parameters.
  460. /// The public key is calculated from the private key.
  461. ed25519Signer(const byte x[SECRET_KEYLENGTH]);
  462. /// \brief Create an ed25519Signer object
  463. /// \param y public key
  464. /// \param x private key
  465. /// \details This constructor creates an ed25519Signer object using existing parameters.
  466. /// \note The public key is not validated.
  467. ed25519Signer(const Integer &y, const Integer &x);
  468. /// \brief Create an ed25519Signer object
  469. /// \param x private key
  470. /// \details This constructor creates an ed25519Signer object using existing parameters.
  471. /// The public key is calculated from the private key.
  472. ed25519Signer(const Integer &x);
  473. /// \brief Create an ed25519Signer object
  474. /// \param key PKCS8 private key
  475. /// \details This constructor creates an ed25519Signer object using existing private key.
  476. /// \note The keys are not validated.
  477. /// \since Crypto++ 8.6
  478. ed25519Signer(const PKCS8PrivateKey &key);
  479. /// \brief Create an ed25519Signer object
  480. /// \param rng RandomNumberGenerator derived class
  481. /// \details This constructor creates a new ed25519Signer using the random number generator.
  482. ed25519Signer(RandomNumberGenerator &rng);
  483. /// \brief Create an ed25519Signer object
  484. /// \param params public and private key
  485. /// \details This constructor creates an ed25519Signer object using existing parameters.
  486. /// The <tt>params</tt> can be created with <tt>Save</tt>.
  487. /// \note The public key is not validated.
  488. ed25519Signer(BufferedTransformation &params);
  489. // DL_ObjectImplBase
  490. /// \brief Retrieves a reference to a Private Key
  491. /// \details AccessKey() retrieves a non-const reference to a private key.
  492. PrivateKey& AccessKey() { return m_key; }
  493. PrivateKey& AccessPrivateKey() { return m_key; }
  494. /// \brief Retrieves a reference to a Private Key
  495. /// \details AccessKey() retrieves a const reference to a private key.
  496. const PrivateKey& GetKey() const { return m_key; }
  497. const PrivateKey& GetPrivateKey() const { return m_key; }
  498. // DL_SignatureSchemeBase
  499. size_t SignatureLength() const { return SIGNATURE_LENGTH; }
  500. size_t MaxRecoverableLength() const { return 0; }
  501. size_t MaxRecoverableLengthFromSignatureLength(size_t signatureLength) const {
  502. CRYPTOPP_UNUSED(signatureLength); return 0;
  503. }
  504. bool IsProbabilistic() const { return false; }
  505. bool AllowNonrecoverablePart() const { return false; }
  506. bool RecoverablePartFirst() const { return false; }
  507. PK_MessageAccumulator* NewSignatureAccumulator(RandomNumberGenerator &rng) const {
  508. return new ed25519_MessageAccumulator(rng);
  509. }
  510. void InputRecoverableMessage(PK_MessageAccumulator &messageAccumulator, const byte *recoverableMessage, size_t recoverableMessageLength) const {
  511. CRYPTOPP_UNUSED(messageAccumulator); CRYPTOPP_UNUSED(recoverableMessage);
  512. CRYPTOPP_UNUSED(recoverableMessageLength);
  513. throw NotImplemented("ed25519Signer: this object does not support recoverable messages");
  514. }
  515. size_t SignAndRestart(RandomNumberGenerator &rng, PK_MessageAccumulator &messageAccumulator, byte *signature, bool restart) const;
  516. /// \brief Sign a stream
  517. /// \param rng a RandomNumberGenerator derived class
  518. /// \param stream an std::istream derived class
  519. /// \param signature a block of bytes for the signature
  520. /// \return actual signature length
  521. /// \details SignStream() handles large streams. The Stream functions were added to
  522. /// ed25519 for signing and verifying files that are too large for a memory allocation.
  523. /// The functions are not present in other library signers and verifiers.
  524. /// \details ed25519 is a deterministic signature scheme. <tt>IsProbabilistic()</tt>
  525. /// returns false and the random number generator can be <tt>NullRNG()</tt>.
  526. /// \pre <tt>COUNTOF(signature) == MaxSignatureLength()</tt>
  527. /// \since Crypto++ 8.1
  528. size_t SignStream (RandomNumberGenerator &rng, std::istream& stream, byte *signature) const;
  529. protected:
  530. ed25519PrivateKey m_key;
  531. };
  532. // ****************** ed25519 Verifier *********************** //
  533. /// \brief Ed25519 public key
  534. /// \details ed25519PublicKey is somewhat of a hack. It needed to
  535. /// provide DL_PublicKey interface to fit into the existing
  536. /// framework, but it lacks a lot of the internals of a true
  537. /// DL_PublicKey. The missing pieces include GroupParameters
  538. /// and Point, which provide the low level field operations
  539. /// found in traditional implementations like NIST curves over
  540. /// prime and binary fields.
  541. /// \details ed25519PublicKey is also unusual because the
  542. /// class members of interest are byte arrays and not Integers.
  543. /// In addition, the byte arrays are little-endian meaning
  544. /// LSB is at element 0 and the MSB is at element 31.
  545. /// If you call GetPublicElement() then the little-endian byte
  546. /// array is converted to a big-endian Integer() so it can be
  547. /// returned the way a caller expects. And calling
  548. /// SetPublicElement() performs a similar internal conversion.
  549. /// \since Crypto++ 8.0
  550. struct ed25519PublicKey : public X509PublicKey
  551. {
  552. /// \brief Size of the public key
  553. /// \details PUBLIC_KEYLENGTH is the size of the public key, in bytes.
  554. CRYPTOPP_CONSTANT(PUBLIC_KEYLENGTH = 32);
  555. typedef Integer Element;
  556. virtual ~ed25519PublicKey() {}
  557. OID GetAlgorithmID() const {
  558. return m_oid.Empty() ? ASN1::Ed25519() : m_oid;
  559. }
  560. /// \brief DER encode ASN.1 object
  561. /// \param bt BufferedTransformation object
  562. /// \details Save() will write the OID associated with algorithm or scheme.
  563. /// In the case of public and private keys, this function writes the
  564. /// subjectPublicKeyInfo parts.
  565. /// \details The default OID is from RFC 8410 using <tt>id-X25519</tt>.
  566. /// The default private key format is RFC 5208, which is the old format.
  567. /// The old format provides the best interop, and keys will work
  568. /// with OpenSSL.
  569. void Save(BufferedTransformation &bt) const {
  570. DEREncode(bt);
  571. }
  572. /// \brief BER decode ASN.1 object
  573. /// \param bt BufferedTransformation object
  574. /// \sa <A HREF="http://tools.ietf.org/rfc/rfc5958.txt">RFC 5958, Asymmetric
  575. /// Key Packages</A>
  576. void Load(BufferedTransformation &bt) {
  577. BERDecode(bt);
  578. }
  579. // X509PublicKey
  580. void BERDecode(BufferedTransformation &bt);
  581. void DEREncode(BufferedTransformation &bt) const;
  582. void BERDecodePublicKey(BufferedTransformation &bt, bool parametersPresent, size_t size);
  583. void DEREncodePublicKey(BufferedTransformation &bt) const;
  584. /// \brief Determine if OID is valid for this object
  585. /// \details BERDecodeAndCheckAlgorithmID() parses the OID from
  586. /// <tt>bt</tt> and determines if it valid for this object. The
  587. /// problem in practice is there are multiple OIDs available to
  588. /// denote curve25519 operations. The OIDs include an old GNU
  589. /// OID used by SSH, OIDs specified in draft-josefsson-pkix-newcurves,
  590. /// and OIDs specified in draft-ietf-curdle-pkix.
  591. /// \details By default BERDecodeAndCheckAlgorithmID() accepts an
  592. /// OID set by the user, <tt>ASN1::curve25519()</tt> and <tt>ASN1::Ed25519()</tt>.
  593. /// <tt>ASN1::curve25519()</tt> is generic and says "this key is valid for
  594. /// curve25519 operations". <tt>ASN1::Ed25519()</tt> is specific and says
  595. /// "this key is valid for ed25519 signing."
  596. void BERDecodeAndCheckAlgorithmID(BufferedTransformation& bt);
  597. bool Validate(RandomNumberGenerator &rng, unsigned int level) const;
  598. bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const;
  599. void AssignFrom(const NameValuePairs &source);
  600. // DL_PublicKey
  601. void SetPublicElement(const byte y[PUBLIC_KEYLENGTH]);
  602. void SetPublicElement(const Element &y);
  603. const Element& GetPublicElement() const;
  604. /// \brief Retrieve public key byte array
  605. /// \return the public key byte array
  606. /// \details GetPublicKeyBytePtr() is used by signing code to call ed25519_sign.
  607. const byte* GetPublicKeyBytePtr() const {
  608. return m_pk.begin();
  609. }
  610. protected:
  611. FixedSizeSecBlock<byte, PUBLIC_KEYLENGTH> m_pk;
  612. OID m_oid; // preferred OID
  613. mutable Integer m_y; // for DL_PublicKey
  614. };
  615. /// \brief Ed25519 signature verification algorithm
  616. /// \since Crypto++ 8.0
  617. struct ed25519Verifier : public PK_Verifier
  618. {
  619. CRYPTOPP_CONSTANT(PUBLIC_KEYLENGTH = 32);
  620. CRYPTOPP_CONSTANT(SIGNATURE_LENGTH = 64);
  621. typedef Integer Element;
  622. virtual ~ed25519Verifier() {}
  623. /// \brief Create an ed25519Verifier object
  624. ed25519Verifier() {}
  625. /// \brief Create an ed25519Verifier object
  626. /// \param y public key
  627. /// \details This constructor creates an ed25519Verifier object using existing parameters.
  628. /// \note The public key is not validated.
  629. ed25519Verifier(const byte y[PUBLIC_KEYLENGTH]);
  630. /// \brief Create an ed25519Verifier object
  631. /// \param y public key
  632. /// \details This constructor creates an ed25519Verifier object using existing parameters.
  633. /// \note The public key is not validated.
  634. ed25519Verifier(const Integer &y);
  635. /// \brief Create an ed25519Verifier object
  636. /// \param key X509 public key
  637. /// \details This constructor creates an ed25519Verifier object using an existing public key.
  638. /// \note The public key is not validated.
  639. /// \since Crypto++ 8.6
  640. ed25519Verifier(const X509PublicKey &key);
  641. /// \brief Create an ed25519Verifier object
  642. /// \param params public and private key
  643. /// \details This constructor creates an ed25519Verifier object using existing parameters.
  644. /// The <tt>params</tt> can be created with <tt>Save</tt>.
  645. /// \note The public key is not validated.
  646. ed25519Verifier(BufferedTransformation &params);
  647. /// \brief Create an ed25519Verifier object
  648. /// \param signer ed25519 signer object
  649. /// \details This constructor creates an ed25519Verifier object using existing parameters.
  650. /// The <tt>params</tt> can be created with <tt>Save</tt>.
  651. /// \note The public key is not validated.
  652. ed25519Verifier(const ed25519Signer& signer);
  653. // DL_ObjectImplBase
  654. /// \brief Retrieves a reference to a Public Key
  655. /// \details AccessKey() retrieves a non-const reference to a public key.
  656. PublicKey& AccessKey() { return m_key; }
  657. PublicKey& AccessPublicKey() { return m_key; }
  658. /// \brief Retrieves a reference to a Public Key
  659. /// \details GetKey() retrieves a const reference to a public key.
  660. const PublicKey& GetKey() const { return m_key; }
  661. const PublicKey& GetPublicKey() const { return m_key; }
  662. // DL_SignatureSchemeBase
  663. size_t SignatureLength() const { return SIGNATURE_LENGTH; }
  664. size_t MaxRecoverableLength() const { return 0; }
  665. size_t MaxRecoverableLengthFromSignatureLength(size_t signatureLength) const {
  666. CRYPTOPP_UNUSED(signatureLength); return 0;
  667. }
  668. bool IsProbabilistic() const { return false; }
  669. bool AllowNonrecoverablePart() const { return false; }
  670. bool RecoverablePartFirst() const { return false; }
  671. ed25519_MessageAccumulator* NewVerificationAccumulator() const {
  672. return new ed25519_MessageAccumulator;
  673. }
  674. void InputSignature(PK_MessageAccumulator &messageAccumulator, const byte *signature, size_t signatureLength) const {
  675. CRYPTOPP_ASSERT(signature != NULLPTR);
  676. CRYPTOPP_ASSERT(signatureLength == SIGNATURE_LENGTH);
  677. ed25519_MessageAccumulator& accum = static_cast<ed25519_MessageAccumulator&>(messageAccumulator);
  678. if (signature && signatureLength)
  679. std::memcpy(accum.signature(), signature, STDMIN((size_t)SIGNATURE_LENGTH, signatureLength));
  680. }
  681. bool VerifyAndRestart(PK_MessageAccumulator &messageAccumulator) const;
  682. /// \brief Check whether input signature is a valid signature for input message
  683. /// \param stream an std::istream derived class
  684. /// \param signature a pointer to the signature over the message
  685. /// \param signatureLen the size of the signature
  686. /// \return true if the signature is valid, false otherwise
  687. /// \details VerifyStream() handles large streams. The Stream functions were added to
  688. /// ed25519 for signing and verifying files that are too large for a memory allocation.
  689. /// The functions are not present in other library signers and verifiers.
  690. /// \since Crypto++ 8.1
  691. bool VerifyStream(std::istream& stream, const byte *signature, size_t signatureLen) const;
  692. DecodingResult RecoverAndRestart(byte *recoveredMessage, PK_MessageAccumulator &messageAccumulator) const {
  693. CRYPTOPP_UNUSED(recoveredMessage); CRYPTOPP_UNUSED(messageAccumulator);
  694. throw NotImplemented("ed25519Verifier: this object does not support recoverable messages");
  695. }
  696. protected:
  697. ed25519PublicKey m_key;
  698. };
  699. /// \brief Ed25519 signature scheme
  700. /// \sa <A HREF="http://cryptopp.com/wiki/Ed25519">Ed25519</A> on the Crypto++ wiki.
  701. /// \since Crypto++ 8.0
  702. struct ed25519
  703. {
  704. /// \brief ed25519 Signer
  705. typedef ed25519Signer Signer;
  706. /// \brief ed25519 Verifier
  707. typedef ed25519Verifier Verifier;
  708. };
  709. NAMESPACE_END // CryptoPP
  710. #endif // CRYPTOPP_XED25519_H