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 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
|
/*************************************************
* Buffered EntropySource Source File *
* (C) 1999-2005 The Botan Project *
*************************************************/
#include <botan/buf_es.h>
#include <botan/bit_ops.h>
#include <botan/util.h>
namespace Botan {
/*************************************************
* Buffered_EntropySource Constructor *
*************************************************/
Buffered_EntropySource::Buffered_EntropySource() : buffer(256)
{
read_pos = write_pos = 0;
done_slow_poll = false;
}
/*************************************************
* Fast Poll *
*************************************************/
u32bit Buffered_EntropySource::fast_poll(byte out[], u32bit length)
{
if(!done_slow_poll) { do_slow_poll(); done_slow_poll = true; }
do_fast_poll();
return copy_out(out, length, buffer.size() / 4);
}
/*************************************************
* Slow Poll *
*************************************************/
u32bit Buffered_EntropySource::slow_poll(byte out[], u32bit length)
{
do_slow_poll();
return copy_out(out, length, buffer.size());
}
/*************************************************
* Default fast poll operation *
*************************************************/
void Buffered_EntropySource::do_fast_poll()
{
return do_slow_poll();
}
/*************************************************
* Add entropy to the internal buffer *
*************************************************/
void Buffered_EntropySource::add_bytes(const void* entropy_ptr, u32bit length)
{
const byte* bytes = (const byte*)entropy_ptr;
while(length)
{
u32bit copied = std::min(length, buffer.size() - write_pos);
xor_buf(buffer + write_pos, bytes, copied);
bytes += copied;
length -= copied;
write_pos = (write_pos + copied) % buffer.size();
}
}
/*************************************************
* Add entropy to the internal buffer *
*************************************************/
void Buffered_EntropySource::add_bytes(u64bit entropy)
{
add_bytes((const void*)&entropy, 8);
}
/*************************************************
* Add entropy to the internal buffer *
*************************************************/
void Buffered_EntropySource::add_timestamp()
{
add_bytes(system_clock());
}
/*************************************************
* Take entropy from the internal buffer *
*************************************************/
u32bit Buffered_EntropySource::copy_out(byte out[], u32bit length,
u32bit max_read)
{
length = std::min(length, max_read);
u32bit copied = std::min(length, buffer.size() - read_pos);
xor_buf(out, buffer + read_pos, copied);
read_pos = (read_pos + copied) % buffer.size();
return copied;
}
}
|