Crypto++
randpool.cpp
1 // randpool.cpp - written and placed in the public domain by Wei Dai
2 // RandomPool used to follow the design of randpool in PGP 2.6.x,
3 // but as of version 5.5 it has been redesigned to reduce the risk
4 // of reusing random numbers after state rollback (which may occur
5 // when running in a virtual machine like VMware).
6 
7 #include "pch.h"
8 
9 #ifndef CRYPTOPP_IMPORTS
10 
11 #include "randpool.h"
12 #include "aes.h"
13 #include "sha.h"
14 #include "hrtimer.h"
15 #include <time.h>
16 
17 NAMESPACE_BEGIN(CryptoPP)
18 
20  : m_pCipher(new AES::Encryption), m_keySet(false)
21 {
22  memset(m_key, 0, m_key.SizeInBytes());
23  memset(m_seed, 0, m_seed.SizeInBytes());
24 }
25 
26 void RandomPool::IncorporateEntropy(const byte *input, size_t length)
27 {
28  SHA256 hash;
29  hash.Update(m_key, 32);
30  hash.Update(input, length);
31  hash.Final(m_key);
32  m_keySet = false;
33 }
34 
35 void RandomPool::GenerateIntoBufferedTransformation(BufferedTransformation &target, const std::string &channel, lword size)
36 {
37  if (size > 0)
38  {
39  if (!m_keySet)
40  m_pCipher->SetKey(m_key, 32);
41 
42  Timer timer;
43  TimerWord tw = timer.GetCurrentTimerValue();
44  CRYPTOPP_COMPILE_ASSERT(sizeof(tw) <= 16);
45  *(TimerWord *)m_seed.data() += tw;
46 
47  time_t t = time(NULL);
48  CRYPTOPP_COMPILE_ASSERT(sizeof(t) <= 8);
49  *(time_t *)(m_seed.data()+8) += t;
50 
51  do
52  {
53  m_pCipher->ProcessBlock(m_seed);
54  size_t len = UnsignedMin(16, size);
55  target.ChannelPut(channel, m_seed, len);
56  size -= len;
57  } while (size > 0);
58  }
59 }
60 
61 NAMESPACE_END
62 
63 #endif