1 /*
2 * Blinding for public key operations
3 * (C) 1999-2010,2015 Jack Lloyd
4 *
5 * Botan is released under the Simplified BSD License (see license.txt)
6 */
7 
8 #ifndef BOTAN_BLINDER_H_
9 #define BOTAN_BLINDER_H_
10 
11 #include <botan/bigint.h>
12 #include <botan/reducer.h>
13 #include <functional>
14 
15 BOTAN_FUTURE_INTERNAL_HEADER(blinding.h)
16 
17 namespace Botan {
18 
19 class RandomNumberGenerator;
20 
21 /**
22 * Blinding Function Object.
23 */
24 class BOTAN_PUBLIC_API(2,0) Blinder final
25    {
26    public:
27       /**
28       * Blind a value.
29       * The blinding nonce k is freshly generated after
30       * BOTAN_BLINDING_REINIT_INTERVAL calls to blind().
31       * BOTAN_BLINDING_REINIT_INTERVAL = 0 means a fresh
32       * nonce is only generated once. On every other call,
33       * an updated nonce is used for blinding: k' = k*k mod n.
34       * @param x value to blind
35       * @return blinded value
36       */
37       BigInt blind(const BigInt& x) const;
38 
39       /**
40       * Unblind a value.
41       * @param x value to unblind
42       * @return unblinded value
43       */
44       BigInt unblind(const BigInt& x) const;
45 
46       /**
47       * @param modulus the modulus
48       * @param rng the RNG to use for generating the nonce
49       * @param fwd_func a function that calculates the modular
50       * exponentiation of the public exponent and the given value (the nonce)
51       * @param inv_func a function that calculates the modular inverse
52       * of the given value (the nonce)
53       */
54       Blinder(const BigInt& modulus,
55               RandomNumberGenerator& rng,
56               std::function<BigInt (const BigInt&)> fwd_func,
57               std::function<BigInt (const BigInt&)> inv_func);
58 
59       Blinder(const Blinder&) = delete;
60 
61       Blinder& operator=(const Blinder&) = delete;
62 
rng()63       RandomNumberGenerator& rng() const { return m_rng; }
64 
65    private:
66       BigInt blinding_nonce() const;
67 
68       Modular_Reducer m_reducer;
69       RandomNumberGenerator& m_rng;
70       std::function<BigInt (const BigInt&)> m_fwd_fn;
71       std::function<BigInt (const BigInt&)> m_inv_fn;
72       size_t m_modulus_bits = 0;
73 
74       mutable BigInt m_e, m_d;
75       mutable size_t m_counter = 0;
76    };
77 
78 }
79 
80 #endif
81