1 /**
2 * EntropySource
3 * 
4 * Copyright:
5 * (C) 2008-2009,2014 Jack Lloyd
6 * (C) 2014-2015 Etienne Cimon
7 *
8 * License:
9 * Botan is released under the Simplified BSD License (see LICENSE.md)
10 */
11 module botan.entropy.entropy_src;
12 
13 import memutils.vector;
14 import botan.utils.types;
15 
16 /**
17 * Class used to accumulate the poll results of EntropySources
18 */
19 struct EntropyAccumulator
20 {
21 public:
22     /**
23     * Initialize an EntropyAccumulator
24     * Params:
25     *  accum = a delegate to send the bytes and entropy value
26     */
27     this(bool delegate(const(ubyte)*, size_t len, double) accum)
28     {
29         m_accum_fn = accum; 
30         m_done = false;
31     }
32 
33     ~this() {}
34 
35     /**
36     * Get a cached I/O buffer (purely for minimizing allocation
37     * overhead to polls)
38     *
39     * Params:
40     *  size = requested size for the I/O buffer
41     * Returns: cached I/O buffer for repeated polls
42     */
43     ref SecureVector!ubyte getIoBuffer(size_t size) return
44     {
45         m_io_buffer.clear();
46         m_io_buffer.resize(size);
47         return m_io_buffer;
48     }
49 
50     /**
51     * Returns: if our polling goal has been achieved
52     */
53     bool pollingGoalAchieved() const { return m_done; }
54 
55     /**
56     * Add entropy to the accumulator
57     * Params:
58     *  bytes = the input bytes
59     *  length = specifies how many bytes the input is
60     *  entropy_bits_per_byte = is a best guess at how much
61     * entropy per ubyte is in this input
62     */
63     void add(const void* bytes, size_t length, double entropy_bits_per_byte)
64     {
65         m_done = m_accum_fn(cast(const(ubyte)*)(bytes), length, entropy_bits_per_byte * length);
66     }
67 
68     /**
69     * Add entropy to the accumulator
70     * Params:
71     *  v = is some value
72     *  entropy_bits_per_byte = is a best guess at how much
73     * entropy per ubyte is in this input
74     */
75     void add(T)(in T v, double entropy_bits_per_byte)
76     {
77         add(&v, T.sizeof, entropy_bits_per_byte);
78     }
79 private:
80     bool delegate(const(ubyte)*, size_t, double) m_accum_fn;
81     bool m_done;
82     SecureVector!ubyte m_io_buffer;
83 }
84 
85 /**
86 * Abstract interface to a source of entropy
87 */
88 interface EntropySource
89 {
90 public:
91     /**
92     * Returns: name identifying this entropy source
93     */
94     @property string name() const;
95 
96     /**
97     * Perform an entropy gathering poll
98     * Params:
99     *  accum = is an accumulator object that will be given entropy
100     */
101     void poll(ref EntropyAccumulator accum);
102 }