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