Crypto++ 8.2 Free C++ class library of cryptographic schemes

rw.cpp
1 // rw.cpp - originally written and placed in the public domain by Wei Dai
2
3 #include "pch.h"
4
5 #include "rw.h"
6 #include "asn.h"
7 #include "integer.h"
8 #include "nbtheory.h"
9 #include "modarith.h"
10 #include "asn.h"
11
12 #ifndef CRYPTOPP_IMPORTS
13
14 #if defined(_OPENMP)
15 # define CRYPTOPP_RW_USE_OMP 1
16 #else
17 # define CRYPTOPP_RW_USE_OMP 0
18 #endif
19
20 NAMESPACE_BEGIN(CryptoPP)
21
22 void RWFunction::BERDecode(BufferedTransformation &bt)
23 {
24 BERSequenceDecoder seq(bt);
25 m_n.BERDecode(seq);
26 seq.MessageEnd();
27 }
28
29 void RWFunction::DEREncode(BufferedTransformation &bt) const
30 {
31 DERSequenceEncoder seq(bt);
32 m_n.DEREncode(seq);
33 seq.MessageEnd();
34 }
35
36 Integer RWFunction::ApplyFunction(const Integer &in) const
37 {
38 DoQuickSanityCheck();
39
40 Integer out = in.Squared()%m_n;
41 const word r = 12;
42 // this code was written to handle both r = 6 and r = 12,
43 // but now only r = 12 is used in P1363
44 const word r2 = r/2;
45 const word r3a = (16 + 5 - r) % 16; // n%16 could be 5 or 13
46 const word r3b = (16 + 13 - r) % 16;
47 const word r4 = (8 + 5 - r/2) % 8; // n%8 == 5
48 switch (out % 16)
49 {
50 case r:
51 break;
52 case r2:
53 case r2+8:
54 out <<= 1;
55 break;
56 case r3a:
57 case r3b:
58 out.Negate();
59 out += m_n;
60 break;
61 case r4:
62 case r4+8:
63 out.Negate();
64 out += m_n;
65 out <<= 1;
66 break;
67 default:
68 out = Integer::Zero();
69 }
70 return out;
71 }
72
73 bool RWFunction::Validate(RandomNumberGenerator &rng, unsigned int level) const
74 {
75 CRYPTOPP_UNUSED(rng), CRYPTOPP_UNUSED(level);
76 bool pass = true;
77 pass = pass && m_n > Integer::One() && m_n%8 == 5;
78 CRYPTOPP_ASSERT(pass);
79 return pass;
80 }
81
82 bool RWFunction::GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
83 {
84 return GetValueHelper(this, name, valueType, pValue).Assignable()
85 CRYPTOPP_GET_FUNCTION_ENTRY(Modulus)
86 ;
87 }
88
89 void RWFunction::AssignFrom(const NameValuePairs &source)
90 {
91 AssignFromHelper(this, source)
92 CRYPTOPP_SET_FUNCTION_ENTRY(Modulus)
93 ;
94 }
95
96 // *****************************************************************************
97 // private key operations:
98
99 // generate a random private key
100 void InvertibleRWFunction::GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &alg)
101 {
102 int modulusSize = 2048;
103 alg.GetIntValue("ModulusSize", modulusSize) || alg.GetIntValue("KeySize", modulusSize);
104
105 if (modulusSize < 16)
106 throw InvalidArgument("InvertibleRWFunction: specified modulus length is too small");
107
108 AlgorithmParameters primeParam = MakeParametersForTwoPrimesOfEqualSize(modulusSize);
109 m_p.GenerateRandom(rng, CombinedNameValuePairs(primeParam, MakeParameters("EquivalentTo", 3)("Mod", 8)));
110 m_q.GenerateRandom(rng, CombinedNameValuePairs(primeParam, MakeParameters("EquivalentTo", 7)("Mod", 8)));
111
112 m_n = m_p * m_q;
113 m_u = m_q.InverseMod(m_p);
114
115 Precompute();
116 }
117
118 void InvertibleRWFunction::Initialize(const Integer &n, const Integer &p, const Integer &q, const Integer &u)
119 {
120 m_n = n; m_p = p; m_q = q; m_u = u;
121
122 Precompute();
123 }
124
125 void InvertibleRWFunction::PrecomputeTweakedRoots() const
126 {
127 ModularArithmetic modp(m_p), modq(m_q);
128
129 // GCC warning bug, https://stackoverflow.com/q/12842306/608639
130 #ifdef _OPENMP
131 #pragma omp parallel sections if(CRYPTOPP_RW_USE_OMP)
132 {
133 #pragma omp section
134 m_pre_2_9p = modp.Exponentiate(2, (9 * m_p - 11)/8);
135 #pragma omp section
136 m_pre_2_3q = modq.Exponentiate(2, (3 * m_q - 5)/8);
137 #pragma omp section
138 m_pre_q_p = modp.Exponentiate(m_q, m_p - 2);
139 }
140 #else
141 m_pre_2_9p = modp.Exponentiate(2, (9 * m_p - 11)/8);
142 m_pre_2_3q = modq.Exponentiate(2, (3 * m_q - 5)/8);
143 m_pre_q_p = modp.Exponentiate(m_q, m_p - 2);
144 #endif
145
146 m_precompute = true;
147 }
148
149 void InvertibleRWFunction::LoadPrecomputation(BufferedTransformation &bt)
150 {
151 BERSequenceDecoder seq(bt);
152 m_pre_2_9p.BERDecode(seq);
153 m_pre_2_3q.BERDecode(seq);
154 m_pre_q_p.BERDecode(seq);
155 seq.MessageEnd();
156
157 m_precompute = true;
158 }
159
160 void InvertibleRWFunction::SavePrecomputation(BufferedTransformation &bt) const
161 {
162 if(!m_precompute)
163 Precompute();
164
165 DERSequenceEncoder seq(bt);
166 m_pre_2_9p.DEREncode(seq);
167 m_pre_2_3q.DEREncode(seq);
168 m_pre_q_p.DEREncode(seq);
169 seq.MessageEnd();
170 }
171
172 void InvertibleRWFunction::BERDecode(BufferedTransformation &bt)
173 {
174 BERSequenceDecoder seq(bt);
175 m_n.BERDecode(seq);
176 m_p.BERDecode(seq);
177 m_q.BERDecode(seq);
178 m_u.BERDecode(seq);
179 seq.MessageEnd();
180
181 m_precompute = false;
182 }
183
184 void InvertibleRWFunction::DEREncode(BufferedTransformation &bt) const
185 {
186 DERSequenceEncoder seq(bt);
187 m_n.DEREncode(seq);
188 m_p.DEREncode(seq);
189 m_q.DEREncode(seq);
190 m_u.DEREncode(seq);
191 seq.MessageEnd();
192 }
193
194 // DJB's "RSA signatures and Rabin-Williams signatures..." (http://cr.yp.to/sigs/rwsota-20080131.pdf).
195 Integer InvertibleRWFunction::CalculateInverse(RandomNumberGenerator &rng, const Integer &x) const
196 {
197 DoQuickSanityCheck();
198
199 if(!m_precompute)
200 Precompute();
201
202 ModularArithmetic modn(m_n), modp(m_p), modq(m_q);
203 Integer r, rInv;
204
205 do
206 {
207 // Do this in a loop for people using small numbers for testing
208 r.Randomize(rng, Integer::One(), m_n - Integer::One());
209 // Fix for CVE-2015-2141. Thanks to Evgeny Sidorov for reporting.
210 // Squaring to satisfy Jacobi requirements suggested by Jean-Pierre Munch.
211 r = modn.Square(r);
212 rInv = modn.MultiplicativeInverse(r);
213 } while (rInv.IsZero());
214
215 Integer re = modn.Square(r);
216 re = modn.Multiply(re, x); // blind
217
218 const Integer &h = re, &p = m_p, &q = m_q;
219 Integer e, f;
220
221 const Integer U = modq.Exponentiate(h, (q+1)/8);
222 if(((modq.Exponentiate(U, 4) - h) % q).IsZero())
223 e = Integer::One();
224 else
225 e = -1;
226
227 const Integer eh = e*h, V = modp.Exponentiate(eh, (p-3)/8);
228 if(((modp.Multiply(modp.Exponentiate(V, 4), modp.Exponentiate(eh, 2)) - eh) % p).IsZero())
229 f = Integer::One();
230 else
231 f = 2;
232
233 #ifdef _OPENMP
234 Integer W, X;
235 #pragma omp parallel sections if(CRYPTOPP_RW_USE_OMP)
236 {
237 #pragma omp section
238 {
239 W = (f.IsUnit() ? U : modq.Multiply(m_pre_2_3q, U));
240 }
241 #pragma omp section
242 {
243 const Integer t = modp.Multiply(modp.Exponentiate(V, 3), eh);
244 X = (f.IsUnit() ? t : modp.Multiply(m_pre_2_9p, t));
245 }
246 }
247 #else
248 const Integer W = (f.IsUnit() ? U : modq.Multiply(m_pre_2_3q, U));
249 const Integer t = modp.Multiply(modp.Exponentiate(V, 3), eh);
250 const Integer X = (f.IsUnit() ? t : modp.Multiply(m_pre_2_9p, t));
251 #endif
252
253 const Integer Y = W + q * modp.Multiply(m_pre_q_p, (X - W));
254
255 // Signature
256 Integer s = modn.Multiply(modn.Square(Y), rInv);
257 CRYPTOPP_ASSERT((e * f * s.Squared()) % m_n == x);
258
259 // IEEE P1363, Section 8.2.8 IFSP-RW, p.44
260 s = STDMIN(s, m_n - s);
261 if (ApplyFunction(s) != x) // check
262 throw Exception(Exception::OTHER_ERROR, "InvertibleRWFunction: computational error during private key operation");
263
264 return s;
265 }
266
267 bool InvertibleRWFunction::Validate(RandomNumberGenerator &rng, unsigned int level) const
268 {
269 bool pass = RWFunction::Validate(rng, level);
270 CRYPTOPP_ASSERT(pass);
271 pass = pass && m_p > Integer::One() && m_p%8 == 3 && m_p < m_n;
272 CRYPTOPP_ASSERT(pass);
273 pass = pass && m_q > Integer::One() && m_q%8 == 7 && m_q < m_n;
274 CRYPTOPP_ASSERT(pass);
275 pass = pass && m_u.IsPositive() && m_u < m_p;
276 CRYPTOPP_ASSERT(pass);
277 if (level >= 1)
278 {
279 pass = pass && m_p * m_q == m_n;
280 CRYPTOPP_ASSERT(pass);
281 pass = pass && m_u * m_q % m_p == 1;
282 CRYPTOPP_ASSERT(pass);
283 }
284 if (level >= 2)
285 {
286 pass = pass && VerifyPrime(rng, m_p, level-2) && VerifyPrime(rng, m_q, level-2);
287 CRYPTOPP_ASSERT(pass);
288 }
289 return pass;
290 }
291
292 bool InvertibleRWFunction::GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
293 {
294 return GetValueHelper<RWFunction>(this, name, valueType, pValue).Assignable()
295 CRYPTOPP_GET_FUNCTION_ENTRY(Prime1)
296 CRYPTOPP_GET_FUNCTION_ENTRY(Prime2)
297 CRYPTOPP_GET_FUNCTION_ENTRY(MultiplicativeInverseOfPrime2ModPrime1)
298 ;
299 }
300
301 void InvertibleRWFunction::AssignFrom(const NameValuePairs &source)
302 {
303 AssignFromHelper<RWFunction>(this, source)
304 CRYPTOPP_SET_FUNCTION_ENTRY(Prime1)
305 CRYPTOPP_SET_FUNCTION_ENTRY(Prime2)
306 CRYPTOPP_SET_FUNCTION_ENTRY(MultiplicativeInverseOfPrime2ModPrime1)
307 ;
308
309 m_precompute = false;
310 }
311
312 NAMESPACE_END
313
314 #endif
Exception
Base class for all exceptions thrown by the library.
Definition: cryptlib.h:158
Name::MultiplicativeInverseOfPrime2ModPrime1
const char * MultiplicativeInverseOfPrime2ModPrime1()
Integer.
Definition: argnames.h:47
CryptoMaterial::Precompute
virtual void Precompute(unsigned int precomputationStorage)
Perform precomputation.
Definition: cryptlib.h:2451
InvalidArgument
An invalid argument was detected.
Definition: cryptlib.h:202
Integer::MultiplicativeInverse
Integer MultiplicativeInverse() const
Calculate multiplicative inverse.
Definition: integer.cpp:4392
InvertibleRWFunction::CalculateInverse
Integer CalculateInverse(RandomNumberGenerator &rng, const Integer &x) const
Calculates the inverse of an element.
Definition: rw.cpp:195
Name::Prime2
const char * Prime2()
Integer.
Definition: argnames.h:44
InvertibleRWFunction::Validate
bool Validate(RandomNumberGenerator &rng, unsigned int level) const
Check this object for errors.
Definition: rw.cpp:267
Integer::DEREncode
void DEREncode(BufferedTransformation &bt) const
Encode in DER format.
Definition: integer.cpp:3433
DERGeneralEncoder::MessageEnd
void MessageEnd()
Signals the end of messages to the object.
Definition: asn.cpp:624
Exception::OTHER_ERROR
Some other error occurred not belonging to other categories.
Definition: cryptlib.h:177
InvertibleRWFunction::Initialize
void Initialize(const Integer &n, const Integer &p, const Integer &q, const Integer &u)
Initialize a Rabin-Williams private key.
Definition: rw.cpp:118
ModularArithmetic
Ring of congruence classes modulo n.
Definition: modarith.h:43
RandomNumberGenerator
Interface for random number generators.
Definition: cryptlib.h:1413
Integer::Randomize
void Randomize(RandomNumberGenerator &rng, size_t bitCount)
Set this Integer to random integer.
Definition: integer.cpp:3504
CombinedNameValuePairs
Combines two sets of NameValuePairs.
Definition: algparam.h:128
Integer::InverseMod
Integer InverseMod(const Integer &n) const
Calculate multiplicative inverse.
Definition: integer.cpp:4421
BERSequenceDecoder
BER Sequence Decoder.
Definition: asn.h:524
BufferedTransformation
Interface for buffered transformations.
Definition: cryptlib.h:1630
RWFunction::ApplyFunction
Integer ApplyFunction(const Integer &x) const
Applies the trapdoor.
Definition: rw.cpp:36
Integer::One
static const Integer &CRYPTOPP_API One()
Integer representing 1.
Definition: integer.cpp:4868
InvertibleRWFunction::GenerateRandom
void GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &alg)
Definition: rw.cpp:100
Integer::IsUnit
bool IsUnit() const
Determine if 1 or -1.
Definition: integer.cpp:4387
RWFunction::Validate
bool Validate(RandomNumberGenerator &rng, unsigned int level) const
Check this object for errors.
Definition: rw.cpp:73
Name::Prime1
const char * Prime1()
Integer.
Definition: argnames.h:43
CryptoMaterial::DoQuickSanityCheck
void DoQuickSanityCheck() const
Perform a quick sanity check.
Definition: cryptlib.h:2472
rw.h
Classes for Rabin-Williams signature scheme.
InvertibleRWFunction::GetVoidValue
bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
Get a named value.
Definition: rw.cpp:292
RWFunction::GetVoidValue
bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
Get a named value.
Definition: rw.cpp:82
ModularArithmetic::Multiply
const Integer & Multiply(const Integer &a, const Integer &b) const
Multiplies elements in the ring.
Definition: modarith.h:190
MakeParameters
AlgorithmParameters MakeParameters(const char *name, const T &value, bool throwIfNotUsed=true)
Create an object that implements NameValuePairs.
Definition: algparam.h:508
Integer::IsZero
bool IsZero() const
Determines if the Integer is 0.
Definition: integer.h:333
Integer::Negate
void Negate()
Reverse the Sign of the Integer.
Definition: integer.cpp:4329
RWFunction::AssignFrom
void AssignFrom(const NameValuePairs &source)
Assign values to this object.
Definition: rw.cpp:89
Integer
Multiple precision integer with arithmetic operations.
Definition: integer.h:49
pch.h
Precompiled header file.
AbstractRing::Exponentiate
virtual Element Exponentiate(const Element &a, const Integer &e) const
Raises a base to an exponent in the group.
Definition: algebra.cpp:316
STDMIN
const T & STDMIN(const T &a, const T &b)
Replacement function for std::min.
Definition: misc.h:635
CRYPTOPP_ASSERT
#define CRYPTOPP_ASSERT(exp)
Debugging and diagnostic assertion.
Definition: trap.h:68
InvertibleRWFunction::LoadPrecomputation
virtual void LoadPrecomputation(BufferedTransformation &storedPrecomputation)
Retrieve previously saved precomputation.
Definition: rw.cpp:149
asn.h
Classes and functions for working with ANS.1 objects.
NameValuePairs::GetIntValue
CRYPTOPP_DLL bool GetIntValue(const char *name, int &value) const
Get a named value with type int.
Definition: cryptlib.h:415
BERGeneralDecoder::MessageEnd
void MessageEnd()
Signals the end of messages to the object.
Definition: asn.cpp:553
nbtheory.h
Classes and functions for number theoretic operations.
DERSequenceEncoder
DER Sequence Encoder.
Definition: asn.h:556
Integer::Squared
Integer Squared() const
Multiply this integer by itself.
Definition: integer.h:631
AlgorithmParameters
An object that implements NameValuePairs.
Definition: algparam.h:425
Name::Modulus
const char * Modulus()
Integer.
Definition: argnames.h:33
InvertibleRWFunction::SavePrecomputation
virtual void SavePrecomputation(BufferedTransformation &storedPrecomputation) const
Save precomputation for later use.
Definition: rw.cpp:160
integer.h
Multiple precision integer with arithmetic operations.
Integer::Zero
static const Integer &CRYPTOPP_API Zero()
Integer representing 0.
Definition: integer.cpp:4856
VerifyPrime
CRYPTOPP_DLL bool CRYPTOPP_API VerifyPrime(RandomNumberGenerator &rng, const Integer &p, unsigned int level=1)
Verifies a number is probably prime.
Definition: nbtheory.cpp:247
InvertibleRWFunction::AssignFrom
void AssignFrom(const NameValuePairs &source)
Assign values to this object.
Definition: rw.cpp:301
Integer::BERDecode
void BERDecode(const byte *input, size_t inputLen)
Decode from BER format.
Definition: integer.cpp:3440
modarith.h
Class file for performing modular arithmetic.
CryptoPP
Crypto++ library namespace.
NameValuePairs
Interface for retrieving values given their names.
Definition: cryptlib.h:321