aboutsummaryrefslogtreecommitdiffstats
path: root/src/pbkdf/pgps2k/pgp_s2k.cpp
blob: 9cec7304ca163ae4de98e4e92fa789b7460930f7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/*
* OpenPGP S2K
* (C) 1999-2007 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/

#include <botan/pgp_s2k.h>

namespace Botan {

/*
* Derive a key using the OpenPGP S2K algorithm
*/
OctetString OpenPGP_S2K::derive_key(size_t key_len,
                                    const std::string& passphrase,
                                    const byte salt_buf[], size_t salt_size,
                                    size_t iterations) const
   {
   SecureVector<byte> key(key_len), hash_buf;

   size_t pass = 0, generated = 0,
          total_size = passphrase.size() + salt_size;
   size_t to_hash = std::max(iterations, total_size);

   hash->clear();
   while(key_len > generated)
      {
      for(size_t j = 0; j != pass; ++j)
         hash->update(0);

      size_t left = to_hash;
      while(left >= total_size)
         {
         hash->update(salt_buf, salt_size);
         hash->update(passphrase);
         left -= total_size;
         }
      if(left <= salt_size)
         hash->update(salt_buf, left);
      else
         {
         hash->update(salt_buf, salt_size);
         left -= salt_size;
         hash->update(reinterpret_cast<const byte*>(passphrase.data()), left);
         }

      hash_buf = hash->final();
      key.copy(generated, &hash_buf[0], hash->output_length());
      generated += hash->output_length();
      ++pass;
      }

   return key;
   }

}