pwdbased.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. // pwdbased.h - originally written and placed in the public domain by Wei Dai
  2. // Cutover to KeyDerivationFunction interface by Uri Blumenthal
  3. // Marcel Raad and Jeffrey Walton in March 2018.
  4. /// \file pwdbased.h
  5. /// \brief Password based key derivation functions
  6. #ifndef CRYPTOPP_PWDBASED_H
  7. #define CRYPTOPP_PWDBASED_H
  8. #include "cryptlib.h"
  9. #include "hrtimer.h"
  10. #include "integer.h"
  11. #include "argnames.h"
  12. #include "algparam.h"
  13. #include "hmac.h"
  14. NAMESPACE_BEGIN(CryptoPP)
  15. // ******************** PBKDF1 ********************
  16. /// \brief PBKDF1 from PKCS #5
  17. /// \tparam T a HashTransformation class
  18. /// \sa PasswordBasedKeyDerivationFunction, <A
  19. /// HREF="https://www.cryptopp.com/wiki/PKCS5_PBKDF1">PKCS5_PBKDF1</A>
  20. /// on the Crypto++ wiki
  21. /// \since Crypto++ 2.0
  22. template <class T>
  23. class PKCS5_PBKDF1 : public PasswordBasedKeyDerivationFunction
  24. {
  25. public:
  26. virtual ~PKCS5_PBKDF1() {}
  27. static std::string StaticAlgorithmName () {
  28. const std::string name(std::string("PBKDF1(") +
  29. std::string(T::StaticAlgorithmName()) + std::string(")"));
  30. return name;
  31. }
  32. // KeyDerivationFunction interface
  33. std::string AlgorithmName() const {
  34. return StaticAlgorithmName();
  35. }
  36. // KeyDerivationFunction interface
  37. size_t MaxDerivedKeyLength() const {
  38. return static_cast<size_t>(T::DIGESTSIZE);
  39. }
  40. // KeyDerivationFunction interface
  41. size_t GetValidDerivedLength(size_t keylength) const;
  42. // KeyDerivationFunction interface
  43. virtual size_t DeriveKey(byte *derived, size_t derivedLen, const byte *secret, size_t secretLen,
  44. const NameValuePairs& params = g_nullNameValuePairs) const;
  45. /// \brief Derive a key from a secret seed
  46. /// \param derived the derived output buffer
  47. /// \param derivedLen the size of the derived buffer, in bytes
  48. /// \param purpose a purpose byte
  49. /// \param secret the seed input buffer
  50. /// \param secretLen the size of the secret buffer, in bytes
  51. /// \param salt the salt input buffer
  52. /// \param saltLen the size of the salt buffer, in bytes
  53. /// \param iterations the number of iterations
  54. /// \param timeInSeconds the in seconds
  55. /// \return the number of iterations performed
  56. /// \throw InvalidDerivedKeyLength if <tt>derivedLen</tt> is invalid for the scheme
  57. /// \details DeriveKey() provides a standard interface to derive a key from
  58. /// a seed and other parameters. Each class that derives from KeyDerivationFunction
  59. /// provides an overload that accepts most parameters used by the derivation function.
  60. /// \details If <tt>timeInSeconds</tt> is <tt>&gt; 0.0</tt> then DeriveKey will run for
  61. /// the specified amount of time. If <tt>timeInSeconds</tt> is <tt>0.0</tt> then DeriveKey
  62. /// will run for the specified number of iterations.
  63. /// \details PKCS #5 says PBKDF1 should only take 8-byte salts. This implementation
  64. /// allows salts of any length.
  65. size_t DeriveKey(byte *derived, size_t derivedLen, byte purpose, const byte *secret, size_t secretLen, const byte *salt, size_t saltLen, unsigned int iterations, double timeInSeconds=0) const;
  66. protected:
  67. // KeyDerivationFunction interface
  68. const Algorithm & GetAlgorithm() const {
  69. return *this;
  70. }
  71. };
  72. template <class T>
  73. size_t PKCS5_PBKDF1<T>::GetValidDerivedLength(size_t keylength) const
  74. {
  75. if (keylength > MaxDerivedKeyLength())
  76. return MaxDerivedKeyLength();
  77. return keylength;
  78. }
  79. template <class T>
  80. size_t PKCS5_PBKDF1<T>::DeriveKey(byte *derived, size_t derivedLen,
  81. const byte *secret, size_t secretLen, const NameValuePairs& params) const
  82. {
  83. CRYPTOPP_ASSERT(secret /*&& secretLen*/);
  84. CRYPTOPP_ASSERT(derived && derivedLen);
  85. CRYPTOPP_ASSERT(derivedLen <= MaxDerivedKeyLength());
  86. byte purpose = (byte)params.GetIntValueWithDefault("Purpose", 0);
  87. unsigned int iterations = (unsigned int)params.GetIntValueWithDefault("Iterations", 1);
  88. double timeInSeconds = 0.0f;
  89. (void)params.GetValue("TimeInSeconds", timeInSeconds);
  90. ConstByteArrayParameter salt;
  91. (void)params.GetValue(Name::Salt(), salt);
  92. return DeriveKey(derived, derivedLen, purpose, secret, secretLen, salt.begin(), salt.size(), iterations, timeInSeconds);
  93. }
  94. template <class T>
  95. size_t PKCS5_PBKDF1<T>::DeriveKey(byte *derived, size_t derivedLen, byte purpose, const byte *secret, size_t secretLen, const byte *salt, size_t saltLen, unsigned int iterations, double timeInSeconds) const
  96. {
  97. CRYPTOPP_ASSERT(secret /*&& secretLen*/);
  98. CRYPTOPP_ASSERT(derived && derivedLen);
  99. CRYPTOPP_ASSERT(derivedLen <= MaxDerivedKeyLength());
  100. CRYPTOPP_ASSERT(iterations > 0 || timeInSeconds > 0);
  101. CRYPTOPP_UNUSED(purpose);
  102. ThrowIfInvalidDerivedKeyLength(derivedLen);
  103. // Business logic
  104. if (!iterations) { iterations = 1; }
  105. T hash;
  106. hash.Update(secret, secretLen);
  107. hash.Update(salt, saltLen);
  108. SecByteBlock buffer(hash.DigestSize());
  109. hash.Final(buffer);
  110. unsigned int i;
  111. ThreadUserTimer timer;
  112. if (timeInSeconds)
  113. timer.StartTimer();
  114. for (i=1; i<iterations || (timeInSeconds && (i%128!=0 || timer.ElapsedTimeAsDouble() < timeInSeconds)); i++)
  115. hash.CalculateDigest(buffer, buffer, buffer.size());
  116. if (derived)
  117. std::memcpy(derived, buffer, derivedLen);
  118. return i;
  119. }
  120. // ******************** PKCS5_PBKDF2_HMAC ********************
  121. /// \brief PBKDF2 from PKCS #5
  122. /// \tparam T a HashTransformation class
  123. /// \sa PasswordBasedKeyDerivationFunction, <A
  124. /// HREF="https://www.cryptopp.com/wiki/PKCS5_PBKDF2_HMAC">PKCS5_PBKDF2_HMAC</A>
  125. /// on the Crypto++ wiki
  126. /// \since Crypto++ 2.0
  127. template <class T>
  128. class PKCS5_PBKDF2_HMAC : public PasswordBasedKeyDerivationFunction
  129. {
  130. public:
  131. virtual ~PKCS5_PBKDF2_HMAC() {}
  132. static std::string StaticAlgorithmName () {
  133. const std::string name(std::string("PBKDF2_HMAC(") +
  134. std::string(T::StaticAlgorithmName()) + std::string(")"));
  135. return name;
  136. }
  137. // KeyDerivationFunction interface
  138. std::string AlgorithmName() const {
  139. return StaticAlgorithmName();
  140. }
  141. // KeyDerivationFunction interface
  142. // should multiply by T::DIGESTSIZE, but gets overflow that way
  143. size_t MaxDerivedKeyLength() const {
  144. return 0xffffffffU;
  145. }
  146. // KeyDerivationFunction interface
  147. size_t GetValidDerivedLength(size_t keylength) const;
  148. // KeyDerivationFunction interface
  149. size_t DeriveKey(byte *derived, size_t derivedLen, const byte *secret, size_t secretLen,
  150. const NameValuePairs& params = g_nullNameValuePairs) const;
  151. /// \brief Derive a key from a secret seed
  152. /// \param derived the derived output buffer
  153. /// \param derivedLen the size of the derived buffer, in bytes
  154. /// \param purpose a purpose byte
  155. /// \param secret the seed input buffer
  156. /// \param secretLen the size of the secret buffer, in bytes
  157. /// \param salt the salt input buffer
  158. /// \param saltLen the size of the salt buffer, in bytes
  159. /// \param iterations the number of iterations
  160. /// \param timeInSeconds the in seconds
  161. /// \return the number of iterations performed
  162. /// \throw InvalidDerivedKeyLength if <tt>derivedLen</tt> is invalid for the scheme
  163. /// \details DeriveKey() provides a standard interface to derive a key from
  164. /// a seed and other parameters. Each class that derives from KeyDerivationFunction
  165. /// provides an overload that accepts most parameters used by the derivation function.
  166. /// \details If <tt>timeInSeconds</tt> is <tt>&gt; 0.0</tt> then DeriveKey will run for
  167. /// the specified amount of time. If <tt>timeInSeconds</tt> is <tt>0.0</tt> then DeriveKey
  168. /// will run for the specified number of iterations.
  169. size_t DeriveKey(byte *derived, size_t derivedLen, byte purpose, const byte *secret, size_t secretLen,
  170. const byte *salt, size_t saltLen, unsigned int iterations, double timeInSeconds=0) const;
  171. protected:
  172. // KeyDerivationFunction interface
  173. const Algorithm & GetAlgorithm() const {
  174. return *this;
  175. }
  176. };
  177. template <class T>
  178. size_t PKCS5_PBKDF2_HMAC<T>::GetValidDerivedLength(size_t keylength) const
  179. {
  180. if (keylength > MaxDerivedKeyLength())
  181. return MaxDerivedKeyLength();
  182. return keylength;
  183. }
  184. template <class T>
  185. size_t PKCS5_PBKDF2_HMAC<T>::DeriveKey(byte *derived, size_t derivedLen,
  186. const byte *secret, size_t secretLen, const NameValuePairs& params) const
  187. {
  188. CRYPTOPP_ASSERT(secret /*&& secretLen*/);
  189. CRYPTOPP_ASSERT(derived && derivedLen);
  190. CRYPTOPP_ASSERT(derivedLen <= MaxDerivedKeyLength());
  191. byte purpose = (byte)params.GetIntValueWithDefault("Purpose", 0);
  192. unsigned int iterations = (unsigned int)params.GetIntValueWithDefault("Iterations", 1);
  193. double timeInSeconds = 0.0f;
  194. (void)params.GetValue("TimeInSeconds", timeInSeconds);
  195. ConstByteArrayParameter salt;
  196. (void)params.GetValue(Name::Salt(), salt);
  197. return DeriveKey(derived, derivedLen, purpose, secret, secretLen, salt.begin(), salt.size(), iterations, timeInSeconds);
  198. }
  199. template <class T>
  200. size_t PKCS5_PBKDF2_HMAC<T>::DeriveKey(byte *derived, size_t derivedLen, byte purpose, const byte *secret, size_t secretLen, const byte *salt, size_t saltLen, unsigned int iterations, double timeInSeconds) const
  201. {
  202. CRYPTOPP_ASSERT(secret /*&& secretLen*/);
  203. CRYPTOPP_ASSERT(derived && derivedLen);
  204. CRYPTOPP_ASSERT(derivedLen <= MaxDerivedKeyLength());
  205. CRYPTOPP_ASSERT(iterations > 0 || timeInSeconds > 0);
  206. CRYPTOPP_UNUSED(purpose);
  207. ThrowIfInvalidDerivedKeyLength(derivedLen);
  208. // Business logic
  209. if (!iterations) { iterations = 1; }
  210. // DigestSize check due to https://github.com/weidai11/cryptopp/issues/855
  211. HMAC<T> hmac(secret, secretLen);
  212. if (hmac.DigestSize() == 0)
  213. throw InvalidArgument("PKCS5_PBKDF2_HMAC: DigestSize cannot be 0");
  214. SecByteBlock buffer(hmac.DigestSize());
  215. ThreadUserTimer timer;
  216. unsigned int i=1;
  217. while (derivedLen > 0)
  218. {
  219. hmac.Update(salt, saltLen);
  220. unsigned int j;
  221. for (j=0; j<4; j++)
  222. {
  223. byte b = byte(i >> ((3-j)*8));
  224. hmac.Update(&b, 1);
  225. }
  226. hmac.Final(buffer);
  227. #if CRYPTOPP_MSC_VERSION
  228. const size_t segmentLen = STDMIN(derivedLen, buffer.size());
  229. memcpy_s(derived, segmentLen, buffer, segmentLen);
  230. #else
  231. const size_t segmentLen = STDMIN(derivedLen, buffer.size());
  232. std::memcpy(derived, buffer, segmentLen);
  233. #endif
  234. if (timeInSeconds)
  235. {
  236. timeInSeconds = timeInSeconds / ((derivedLen + buffer.size() - 1) / buffer.size());
  237. timer.StartTimer();
  238. }
  239. for (j=1; j<iterations || (timeInSeconds && (j%128!=0 || timer.ElapsedTimeAsDouble() < timeInSeconds)); j++)
  240. {
  241. hmac.CalculateDigest(buffer, buffer, buffer.size());
  242. xorbuf(derived, buffer, segmentLen);
  243. }
  244. if (timeInSeconds)
  245. {
  246. iterations = j;
  247. timeInSeconds = 0;
  248. }
  249. derived += segmentLen;
  250. derivedLen -= segmentLen;
  251. i++;
  252. }
  253. return iterations;
  254. }
  255. // ******************** PKCS12_PBKDF ********************
  256. /// \brief PBKDF from PKCS #12, appendix B
  257. /// \tparam T a HashTransformation class
  258. /// \sa PasswordBasedKeyDerivationFunction, <A
  259. /// HREF="https://www.cryptopp.com/wiki/PKCS12_PBKDF">PKCS12_PBKDF</A>
  260. /// on the Crypto++ wiki
  261. /// \since Crypto++ 2.0
  262. template <class T>
  263. class PKCS12_PBKDF : public PasswordBasedKeyDerivationFunction
  264. {
  265. public:
  266. virtual ~PKCS12_PBKDF() {}
  267. static std::string StaticAlgorithmName () {
  268. const std::string name(std::string("PBKDF_PKCS12(") +
  269. std::string(T::StaticAlgorithmName()) + std::string(")"));
  270. return name;
  271. }
  272. // KeyDerivationFunction interface
  273. std::string AlgorithmName() const {
  274. return StaticAlgorithmName();
  275. }
  276. // TODO - check this
  277. size_t MaxDerivedKeyLength() const {
  278. return static_cast<size_t>(-1);
  279. }
  280. // KeyDerivationFunction interface
  281. size_t GetValidDerivedLength(size_t keylength) const;
  282. // KeyDerivationFunction interface
  283. size_t DeriveKey(byte *derived, size_t derivedLen, const byte *secret, size_t secretLen,
  284. const NameValuePairs& params = g_nullNameValuePairs) const;
  285. /// \brief Derive a key from a secret seed
  286. /// \param derived the derived output buffer
  287. /// \param derivedLen the size of the derived buffer, in bytes
  288. /// \param purpose a purpose byte
  289. /// \param secret the seed input buffer
  290. /// \param secretLen the size of the secret buffer, in bytes
  291. /// \param salt the salt input buffer
  292. /// \param saltLen the size of the salt buffer, in bytes
  293. /// \param iterations the number of iterations
  294. /// \param timeInSeconds the in seconds
  295. /// \return the number of iterations performed
  296. /// \throw InvalidDerivedKeyLength if <tt>derivedLen</tt> is invalid for the scheme
  297. /// \details DeriveKey() provides a standard interface to derive a key from
  298. /// a seed and other parameters. Each class that derives from KeyDerivationFunction
  299. /// provides an overload that accepts most parameters used by the derivation function.
  300. /// \details If <tt>timeInSeconds</tt> is <tt>&gt; 0.0</tt> then DeriveKey will run for
  301. /// the specified amount of time. If <tt>timeInSeconds</tt> is <tt>0.0</tt> then DeriveKey
  302. /// will run for the specified number of iterations.
  303. size_t DeriveKey(byte *derived, size_t derivedLen, byte purpose, const byte *secret, size_t secretLen,
  304. const byte *salt, size_t saltLen, unsigned int iterations, double timeInSeconds) const;
  305. protected:
  306. // KeyDerivationFunction interface
  307. const Algorithm & GetAlgorithm() const {
  308. return *this;
  309. }
  310. };
  311. template <class T>
  312. size_t PKCS12_PBKDF<T>::GetValidDerivedLength(size_t keylength) const
  313. {
  314. if (keylength > MaxDerivedKeyLength())
  315. return MaxDerivedKeyLength();
  316. return keylength;
  317. }
  318. template <class T>
  319. size_t PKCS12_PBKDF<T>::DeriveKey(byte *derived, size_t derivedLen,
  320. const byte *secret, size_t secretLen, const NameValuePairs& params) const
  321. {
  322. CRYPTOPP_ASSERT(secret /*&& secretLen*/);
  323. CRYPTOPP_ASSERT(derived && derivedLen);
  324. CRYPTOPP_ASSERT(derivedLen <= MaxDerivedKeyLength());
  325. byte purpose = (byte)params.GetIntValueWithDefault("Purpose", 0);
  326. unsigned int iterations = (unsigned int)params.GetIntValueWithDefault("Iterations", 1);
  327. double timeInSeconds = 0.0f;
  328. (void)params.GetValue("TimeInSeconds", timeInSeconds);
  329. // NULL or 0 length salt OK
  330. ConstByteArrayParameter salt;
  331. (void)params.GetValue(Name::Salt(), salt);
  332. return DeriveKey(derived, derivedLen, purpose, secret, secretLen, salt.begin(), salt.size(), iterations, timeInSeconds);
  333. }
  334. template <class T>
  335. size_t PKCS12_PBKDF<T>::DeriveKey(byte *derived, size_t derivedLen, byte purpose, const byte *secret, size_t secretLen, const byte *salt, size_t saltLen, unsigned int iterations, double timeInSeconds) const
  336. {
  337. CRYPTOPP_ASSERT(secret /*&& secretLen*/);
  338. CRYPTOPP_ASSERT(derived && derivedLen);
  339. CRYPTOPP_ASSERT(derivedLen <= MaxDerivedKeyLength());
  340. CRYPTOPP_ASSERT(iterations > 0 || timeInSeconds > 0);
  341. ThrowIfInvalidDerivedKeyLength(derivedLen);
  342. // Business logic
  343. if (!iterations) { iterations = 1; }
  344. const size_t v = T::BLOCKSIZE; // v is in bytes rather than bits as in PKCS #12
  345. const size_t DLen = v, SLen = RoundUpToMultipleOf(saltLen, v);
  346. const size_t PLen = RoundUpToMultipleOf(secretLen, v), ILen = SLen + PLen;
  347. SecByteBlock buffer(DLen + SLen + PLen);
  348. byte *D = buffer, *S = buffer+DLen, *P = buffer+DLen+SLen, *I = S;
  349. if (D) // GCC analyzer
  350. std::memset(D, purpose, DLen);
  351. size_t i;
  352. for (i=0; i<SLen; i++)
  353. S[i] = salt[i % saltLen];
  354. for (i=0; i<PLen; i++)
  355. P[i] = secret[i % secretLen];
  356. T hash;
  357. SecByteBlock Ai(T::DIGESTSIZE), B(v);
  358. ThreadUserTimer timer;
  359. while (derivedLen > 0)
  360. {
  361. hash.CalculateDigest(Ai, buffer, buffer.size());
  362. if (timeInSeconds)
  363. {
  364. timeInSeconds = timeInSeconds / ((derivedLen + Ai.size() - 1) / Ai.size());
  365. timer.StartTimer();
  366. }
  367. for (i=1; i<iterations || (timeInSeconds && (i%128!=0 || timer.ElapsedTimeAsDouble() < timeInSeconds)); i++)
  368. hash.CalculateDigest(Ai, Ai, Ai.size());
  369. if (timeInSeconds)
  370. {
  371. iterations = (unsigned int)i;
  372. timeInSeconds = 0;
  373. }
  374. for (i=0; i<B.size(); i++)
  375. B[i] = Ai[i % Ai.size()];
  376. Integer B1(B, B.size());
  377. ++B1;
  378. for (i=0; i<ILen; i+=v)
  379. (Integer(I+i, v) + B1).Encode(I+i, v);
  380. #if CRYPTOPP_MSC_VERSION
  381. const size_t segmentLen = STDMIN(derivedLen, Ai.size());
  382. memcpy_s(derived, segmentLen, Ai, segmentLen);
  383. #else
  384. const size_t segmentLen = STDMIN(derivedLen, Ai.size());
  385. std::memcpy(derived, Ai, segmentLen);
  386. #endif
  387. derived += segmentLen;
  388. derivedLen -= segmentLen;
  389. }
  390. return iterations;
  391. }
  392. NAMESPACE_END
  393. #endif