MySQL 5.6.14 Source Code Document
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
pwdbased.hpp
1 /*
2  Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.
3 
4  This program is free software; you can redistribute it and/or modify
5  it under the terms of the GNU General Public License as published by
6  the Free Software Foundation; version 2 of the License.
7 
8  This program is distributed in the hope that it will be useful,
9  but WITHOUT ANY WARRANTY; without even the implied warranty of
10  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11  GNU General Public License for more details.
12 
13  You should have received a copy of the GNU General Public License
14  along with this program; see the file COPYING. If not, write to the
15  Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
16  MA 02110-1301 USA.
17 */
18 
19 /* pwdbased.hpp defines PBKDF2 from PKCS #5
20 */
21 
22 
23 #ifndef TAO_CRYPT_PWDBASED_HPP
24 #define TAO_CRYPT_PWDBASED_HPP
25 
26 #include <string.h>
27 #include "misc.hpp"
28 #include "block.hpp"
29 #include "hmac.hpp"
30 
31 namespace TaoCrypt {
32 
33 
34 // From PKCS #5, T must be type suitable for HMAC<T>
35 template <class T>
36 class PBKDF2_HMAC {
37 public:
38  word32 MaxDerivedKeyLength() const { return 0xFFFFFFFFU;} // avoid overflow
39 
40  word32 DeriveKey(byte* derived, word32 dLen, const byte* pwd, word32 pLen,
41  const byte* salt, word32 sLen, word32 iterations) const;
42 };
43 
44 
45 
46 template <class T>
47 word32 PBKDF2_HMAC<T>::DeriveKey(byte* derived, word32 dLen, const byte* pwd,
48  word32 pLen, const byte* salt, word32 sLen,
49  word32 iterations) const
50 {
51  if (dLen > MaxDerivedKeyLength())
52  return 0;
53 
54  if (iterations < 0)
55  return 0;
56 
57  ByteBlock buffer(T::DIGEST_SIZE);
58  HMAC<T> hmac;
59 
60  hmac.SetKey(pwd, pLen);
61 
62  word32 i = 1;
63 
64  while (dLen > 0) {
65  hmac.Update(salt, sLen);
66  word32 j;
67  for (j = 0; j < 4; j++) {
68  byte b = i >> ((3-j)*8);
69  hmac.Update(&b, 1);
70  }
71  hmac.Final(buffer.get_buffer());
72 
73  word32 segmentLen = min(dLen, buffer.size());
74  memcpy(derived, buffer.get_buffer(), segmentLen);
75 
76  for (j = 1; j < iterations; j++) {
77  hmac.Update(buffer.get_buffer(), buffer.size());
78  hmac.Final(buffer.get_buffer());
79  xorbuf(derived, buffer.get_buffer(), segmentLen);
80  }
81  derived += segmentLen;
82  dLen -= segmentLen;
83  i++;
84  }
85  return iterations;
86 }
87 
88 
89 
90 
91 } // naemspace
92 
93 #endif // TAO_CRYPT_PWDBASED_HPP