monotone

monotone Mtn Source Tree

Root/cryptopp/randpool.cpp

1// randpool.cpp - written and placed in the public domain by Wei Dai
2// The algorithm in this module comes from PGP's randpool.c
3
4#include "pch.h"
5#include "randpool.h"
6#include "mdc.h"
7#include "sha.h"
8#include "modes.h"
9
10NAMESPACE_BEGIN(CryptoPP)
11
12typedef MDC<SHA> RandomPoolCipher;
13
14RandomPool::RandomPool(unsigned int poolSize)
15: pool(poolSize), key(RandomPoolCipher::DEFAULT_KEYLENGTH)
16{
17assert(poolSize > key.size());
18
19addPos=0;
20getPos=poolSize;
21memset(pool, 0, poolSize);
22memset(key, 0, key.size());
23}
24
25void RandomPool::Stir()
26{
27CFB_Mode<RandomPoolCipher>::Encryption cipher;
28
29for (int i=0; i<2; i++)
30{
31cipher.SetKeyWithIV(key, key.size(), pool.end()-cipher.IVSize());
32cipher.ProcessString(pool, pool.size());
33memcpy(key, pool, key.size());
34}
35
36addPos = 0;
37getPos = key.size();
38}
39
40unsigned int RandomPool::Put2(const byte *inString, unsigned int length, int messageEnd, bool blocking)
41{
42unsigned t;
43
44while (length > (t = pool.size() - addPos))
45{
46xorbuf(pool+addPos, inString, t);
47inString += t;
48length -= t;
49Stir();
50}
51
52if (length)
53{
54xorbuf(pool+addPos, inString, length);
55addPos += length;
56getPos = pool.size(); // Force stir on get
57}
58
59return 0;
60}
61
62unsigned int RandomPool::TransferTo2(BufferedTransformation &target, unsigned long &transferBytes, const std::string &channel, bool blocking)
63{
64if (!blocking)
65throw NotImplemented("RandomPool: nonblocking transfer is not implemented by this object");
66
67unsigned int t;
68unsigned long size = transferBytes;
69
70while (size > (t = pool.size() - getPos))
71{
72target.ChannelPut(channel, pool+getPos, t);
73size -= t;
74Stir();
75}
76
77if (size)
78{
79target.ChannelPut(channel, pool+getPos, size);
80getPos += size;
81}
82
83return 0;
84}
85
86byte RandomPool::GenerateByte()
87{
88if (getPos == pool.size())
89Stir();
90
91return pool[getPos++];
92}
93
94void RandomPool::GenerateBlock(byte *outString, unsigned int size)
95{
96ArraySink sink(outString, size);
97TransferTo(sink, size);
98}
99
100NAMESPACE_END

Archive Download this file

Branches

Tags

Quick Links:     www.monotone.ca    -     Downloads    -     Documentation    -     Wiki    -     Code Forge    -     Build Status