Crypto++  5.6.5 Free C++ class library of cryptographic schemes
rw.cpp
1 // rw.cpp - 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 static const bool CRYPTOPP_RW_USE_OMP = true;
16 #else
17 static const bool CRYPTOPP_RW_USE_OMP = false;
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
37 {
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  return pass;
79 }
80
81 bool RWFunction::GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
82 {
83  return GetValueHelper(this, name, valueType, pValue).Assignable()
84  CRYPTOPP_GET_FUNCTION_ENTRY(Modulus)
85  ;
86 }
87
89 {
90  AssignFromHelper(this, source)
91  CRYPTOPP_SET_FUNCTION_ENTRY(Modulus)
92  ;
93 }
94
95 // *****************************************************************************
96 // private key operations:
97
98 // generate a random private key
100 {
101  int modulusSize = 2048;
102  alg.GetIntValue("ModulusSize", modulusSize) || alg.GetIntValue("KeySize", modulusSize);
103
104  if (modulusSize < 16)
105  throw InvalidArgument("InvertibleRWFunction: specified modulus length is too small");
106
107  AlgorithmParameters primeParam = MakeParametersForTwoPrimesOfEqualSize(modulusSize);
108  m_p.GenerateRandom(rng, CombinedNameValuePairs(primeParam, MakeParameters("EquivalentTo", 3)("Mod", 8)));
109  m_q.GenerateRandom(rng, CombinedNameValuePairs(primeParam, MakeParameters("EquivalentTo", 7)("Mod", 8)));
110
111  m_n = m_p * m_q;
112  m_u = m_q.InverseMod(m_p);
113
114  Precompute();
115 }
116
117 void InvertibleRWFunction::Initialize(const Integer &n, const Integer &p, const Integer &q, const Integer &u)
118 {
119  m_n = n; m_p = p; m_q = q; m_u = u;
120
121  Precompute();
122 }
123
124 void InvertibleRWFunction::PrecomputeTweakedRoots() const
125 {
126  ModularArithmetic modp(m_p), modq(m_q);
127
128  #pragma omp parallel sections if(CRYPTOPP_RW_USE_OMP)
129  {
130  #pragma omp section
131  m_pre_2_9p = modp.Exponentiate(2, (9 * m_p - 11)/8);
132  #pragma omp section
133  m_pre_2_3q = modq.Exponentiate(2, (3 * m_q - 5)/8);
134  #pragma omp section
135  m_pre_q_p = modp.Exponentiate(m_q, m_p - 2);
136  }
137
138  m_precompute = true;
139 }
140
142 {
143  BERSequenceDecoder seq(bt);
144  m_pre_2_9p.BERDecode(seq);
145  m_pre_2_3q.BERDecode(seq);
146  m_pre_q_p.BERDecode(seq);
147  seq.MessageEnd();
148
149  m_precompute = true;
150 }
151
153 {
154  if(!m_precompute)
155  Precompute();
156
157  DERSequenceEncoder seq(bt);
158  m_pre_2_9p.DEREncode(seq);
159  m_pre_2_3q.DEREncode(seq);
160  m_pre_q_p.DEREncode(seq);
161  seq.MessageEnd();
162 }
163
164 void InvertibleRWFunction::BERDecode(BufferedTransformation &bt)
165 {
166  BERSequenceDecoder seq(bt);
167  m_n.BERDecode(seq);
168  m_p.BERDecode(seq);
169  m_q.BERDecode(seq);
170  m_u.BERDecode(seq);
171  seq.MessageEnd();
172
173  m_precompute = false;
174 }
175
176 void InvertibleRWFunction::DEREncode(BufferedTransformation &bt) const
177 {
178  DERSequenceEncoder seq(bt);
179  m_n.DEREncode(seq);
180  m_p.DEREncode(seq);
181  m_q.DEREncode(seq);
182  m_u.DEREncode(seq);
183  seq.MessageEnd();
184 }
185
186 // DJB's "RSA signatures and Rabin-Williams signatures..." (http://cr.yp.to/sigs/rwsota-20080131.pdf).
188 {
190
191  if(!m_precompute)
192  Precompute();
193
194  ModularArithmetic modn(m_n), modp(m_p), modq(m_q);
195  Integer r, rInv;
196
197  do
198  {
199  // Do this in a loop for people using small numbers for testing
200  r.Randomize(rng, Integer::One(), m_n - Integer::One());
201  // Fix for CVE-2015-2141. Thanks to Evgeny Sidorov for reporting.
202  // Squaring to satisfy Jacobi requirements suggested by Jean-Pierre Munch.
203  r = modn.Square(r);
204  rInv = modn.MultiplicativeInverse(r);
205  } while (rInv.IsZero());
206
207  Integer re = modn.Square(r);
208  re = modn.Multiply(re, x); // blind
209
210  const Integer &h = re, &p = m_p, &q = m_q;
211  Integer e, f;
212
213  const Integer U = modq.Exponentiate(h, (q+1)/8);
214  if(((modq.Exponentiate(U, 4) - h) % q).IsZero())
215  e = Integer::One();
216  else
217  e = -1;
218
219  const Integer eh = e*h, V = modp.Exponentiate(eh, (p-3)/8);
220  if(((modp.Multiply(modp.Exponentiate(V, 4), modp.Exponentiate(eh, 2)) - eh) % p).IsZero())
221  f = Integer::One();
222  else
223  f = 2;
224
225  Integer W, X;
226  #pragma omp parallel sections if(CRYPTOPP_RW_USE_OMP)
227  {
228  #pragma omp section
229  {
230  W = (f.IsUnit() ? U : modq.Multiply(m_pre_2_3q, U));
231  }
232  #pragma omp section
233  {
234  const Integer t = modp.Multiply(modp.Exponentiate(V, 3), eh);
235  X = (f.IsUnit() ? t : modp.Multiply(m_pre_2_9p, t));
236  }
237  }
238  const Integer Y = W + q * modp.Multiply(m_pre_q_p, (X - W));
239
240  // Signature
241  Integer s = modn.Multiply(modn.Square(Y), rInv);
242  CRYPTOPP_ASSERT((e * f * s.Squared()) % m_n == x);
243
244  // IEEE P1363, Section 8.2.8 IFSP-RW, p.44
245  s = STDMIN(s, m_n - s);
246  if (ApplyFunction(s) != x) // check
247  throw Exception(Exception::OTHER_ERROR, "InvertibleRWFunction: computational error during private key operation");
248
249  return s;
250 }
251
252 bool InvertibleRWFunction::Validate(RandomNumberGenerator &rng, unsigned int level) const
253 {
254  bool pass = RWFunction::Validate(rng, level);
255  pass = pass && m_p > Integer::One() && m_p%8 == 3 && m_p < m_n;
256  pass = pass && m_q > Integer::One() && m_q%8 == 7 && m_q < m_n;
257  pass = pass && m_u.IsPositive() && m_u < m_p;
258  if (level >= 1)
259  {
260  pass = pass && m_p * m_q == m_n;
261  pass = pass && m_u * m_q % m_p == 1;
262  }
263  if (level >= 2)
264  pass = pass && VerifyPrime(rng, m_p, level-2) && VerifyPrime(rng, m_q, level-2);
265  return pass;
266 }
267
268 bool InvertibleRWFunction::GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
269 {
270  return GetValueHelper<RWFunction>(this, name, valueType, pValue).Assignable()
271  CRYPTOPP_GET_FUNCTION_ENTRY(Prime1)
272  CRYPTOPP_GET_FUNCTION_ENTRY(Prime2)
273  CRYPTOPP_GET_FUNCTION_ENTRY(MultiplicativeInverseOfPrime2ModPrime1)
274  ;
275 }
276
278 {
279  AssignFromHelper<RWFunction>(this, source)
280  CRYPTOPP_SET_FUNCTION_ENTRY(Prime1)
281  CRYPTOPP_SET_FUNCTION_ENTRY(Prime2)
282  CRYPTOPP_SET_FUNCTION_ENTRY(MultiplicativeInverseOfPrime2ModPrime1)
283  ;
284
285  m_precompute = false;
286 }
287
288 NAMESPACE_END
289
290 #endif
Base class for all exceptions thrown by the library.
Definition: cryptlib.h:144
const char * MultiplicativeInverseOfPrime2ModPrime1()
Integer.
Definition: argnames.h:46
An invalid argument was detected.
Definition: cryptlib.h:187
const char * Prime2()
Integer.
Definition: argnames.h:43
virtual void SavePrecomputation(BufferedTransformation &storedPrecomputation) const
Save precomputation for later use.
Definition: rw.cpp:152
bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
Get a named value.
Definition: rw.cpp:268
Some other error occurred not belonging to other categories.
Definition: cryptlib.h:163
Ring of congruence classes modulo n.
Definition: modarith.h:34
Interface for random number generators.
Definition: cryptlib.h:1201
bool Validate(RandomNumberGenerator &rng, unsigned int level) const
Check this object for errors.
Definition: rw.cpp:73
void Randomize(RandomNumberGenerator &rng, size_t bitCount)
Set this Integer to random integer.
Definition: integer.cpp:3463
Combines two sets of NameValuePairs.
Definition: algparam.h:135
BER Sequence Decoder.
Definition: asn.h:294
Interface for buffered transformations.
Definition: cryptlib.h:1367
Integer MultiplicativeInverse() const
return inverse if 1 or -1, otherwise return 0
Definition: integer.cpp:4218
static const Integer & One()
Integer representing 1.
Definition: integer.cpp:3040
Integer ApplyFunction(const Integer &x) const
Applies the trapdoor.
Definition: rw.cpp:36
bool GetIntValue(const char *name, int &value) const
Get a named value with type int.
Definition: cryptlib.h:376
void GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &alg)
Definition: rw.cpp:99
const char * Prime1()
Integer.
Definition: argnames.h:42
bool IsUnit() const
is 1 or -1
Definition: integer.cpp:4213
const Integer & Multiply(const Integer &a, const Integer &b) const
Multiplies elements in the ring.
Definition: modarith.h:172
Classes for Rabin-Williams signature scheme.
bool IsPositive() const
Determines if the Integer is positive.
Definition: integer.h:338
Integer Squared() const
Definition: integer.h:496
Rabin-Williams trapdoor function using the public key.
Definition: rw.h:22
AlgorithmParameters MakeParameters(const char *name, const T &value, bool throwIfNotUsed=true)
Create an object that implements NameValuePairs.
Definition: algparam.h:563
bool VerifyPrime(RandomNumberGenerator &rng, const Integer &p, unsigned int level=1)
Verifies a prime number.
Definition: nbtheory.cpp:249
void Negate()
Reverse the Sign of the Integer.
Definition: integer.cpp:4154
void AssignFrom(const NameValuePairs &source)
Assign values to this object.
Definition: rw.cpp:88
Multiple precision integer with arithmetic operations.
Definition: integer.h:45
bool Validate(RandomNumberGenerator &rng, unsigned int level) const
Check this object for errors.
Definition: rw.cpp:252
bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
Get a named value.
Definition: rw.cpp:81
const T & STDMIN(const T &a, const T &b)
Replacement function for std::min.
Definition: misc.h:470
#define CRYPTOPP_ASSERT(exp)
Debugging and diagnostic assertion.
Definition: trap.h:62
Retrieve previously saved precomputation.
Definition: rw.cpp:141
bool IsZero() const
Determines if the Integer is 0.
Definition: integer.h:326
Classes and functions for working with ANS.1 objects.
Integer CalculateInverse(RandomNumberGenerator &rng, const Integer &x) const
Calculates the inverse of an element.
Definition: rw.cpp:187
Classes and functions for number theoretic operations.
void DEREncode(BufferedTransformation &bt) const
Encode in DER format.
Definition: integer.cpp:3396
DER Sequence Encoder.
Definition: asn.h:304
An object that implements NameValuePairs.
Definition: algparam.h:498
const char * Modulus()
Integer.
Definition: argnames.h:32
Integer InverseMod(const Integer &n) const
calculate multiplicative inverse of *this mod n
Definition: integer.cpp:4239
Multiple precision integer with arithmetic operations.
static const Integer & Zero()
Integer representing 0.
Definition: integer.cpp:3032
void AssignFrom(const NameValuePairs &source)
Assign values to this object.
Definition: rw.cpp:277
void BERDecode(const byte *input, size_t inputLen)
Decode from BER format.
Definition: integer.cpp:3403
Class file for performing modular arithmetic.
Crypto++ library namespace.
virtual void Precompute(unsigned int unused=0)
Perform precomputation.
Definition: rw.h:94
virtual Element Exponentiate(const Element &a, const Integer &e) const
Raises a base to an exponent in the group.
Definition: algebra.cpp:316
Interface for retrieving values given their names.
Definition: cryptlib.h:282
void DoQuickSanityCheck() const
Perform a quick sanity check.
Definition: cryptlib.h:2164