Crypto++  8.0
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 
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  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 
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
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  #pragma omp parallel sections if(CRYPTOPP_RW_USE_OMP)
130  {
131  #pragma omp section
132  m_pre_2_9p = modp.Exponentiate(2, (9 * m_p - 11)/8);
133  #pragma omp section
134  m_pre_2_3q = modq.Exponentiate(2, (3 * m_q - 5)/8);
135  #pragma omp section
136  m_pre_q_p = modp.Exponentiate(m_q, m_p - 2);
137  }
138 
139  m_precompute = true;
140 }
141 
143 {
144  BERSequenceDecoder seq(bt);
145  m_pre_2_9p.BERDecode(seq);
146  m_pre_2_3q.BERDecode(seq);
147  m_pre_q_p.BERDecode(seq);
148  seq.MessageEnd();
149 
150  m_precompute = true;
151 }
152 
154 {
155  if(!m_precompute)
156  Precompute();
157 
158  DERSequenceEncoder seq(bt);
159  m_pre_2_9p.DEREncode(seq);
160  m_pre_2_3q.DEREncode(seq);
161  m_pre_q_p.DEREncode(seq);
162  seq.MessageEnd();
163 }
164 
165 void InvertibleRWFunction::BERDecode(BufferedTransformation &bt)
166 {
167  BERSequenceDecoder seq(bt);
168  m_n.BERDecode(seq);
169  m_p.BERDecode(seq);
170  m_q.BERDecode(seq);
171  m_u.BERDecode(seq);
172  seq.MessageEnd();
173 
174  m_precompute = false;
175 }
176 
177 void InvertibleRWFunction::DEREncode(BufferedTransformation &bt) const
178 {
179  DERSequenceEncoder seq(bt);
180  m_n.DEREncode(seq);
181  m_p.DEREncode(seq);
182  m_q.DEREncode(seq);
183  m_u.DEREncode(seq);
184  seq.MessageEnd();
185 }
186 
187 // DJB's "RSA signatures and Rabin-Williams signatures..." (http://cr.yp.to/sigs/rwsota-20080131.pdf).
189 {
191 
192  if(!m_precompute)
193  Precompute();
194 
195  ModularArithmetic modn(m_n), modp(m_p), modq(m_q);
196  Integer r, rInv;
197 
198  do
199  {
200  // Do this in a loop for people using small numbers for testing
201  r.Randomize(rng, Integer::One(), m_n - Integer::One());
202  // Fix for CVE-2015-2141. Thanks to Evgeny Sidorov for reporting.
203  // Squaring to satisfy Jacobi requirements suggested by Jean-Pierre Munch.
204  r = modn.Square(r);
205  rInv = modn.MultiplicativeInverse(r);
206  } while (rInv.IsZero());
207 
208  Integer re = modn.Square(r);
209  re = modn.Multiply(re, x); // blind
210 
211  const Integer &h = re, &p = m_p, &q = m_q;
212  Integer e, f;
213 
214  const Integer U = modq.Exponentiate(h, (q+1)/8);
215  if(((modq.Exponentiate(U, 4) - h) % q).IsZero())
216  e = Integer::One();
217  else
218  e = -1;
219 
220  const Integer eh = e*h, V = modp.Exponentiate(eh, (p-3)/8);
221  if(((modp.Multiply(modp.Exponentiate(V, 4), modp.Exponentiate(eh, 2)) - eh) % p).IsZero())
222  f = Integer::One();
223  else
224  f = 2;
225 
226  Integer W, X;
227  #pragma omp parallel sections if(CRYPTOPP_RW_USE_OMP)
228  {
229  #pragma omp section
230  {
231  W = (f.IsUnit() ? U : modq.Multiply(m_pre_2_3q, U));
232  }
233  #pragma omp section
234  {
235  const Integer t = modp.Multiply(modp.Exponentiate(V, 3), eh);
236  X = (f.IsUnit() ? t : modp.Multiply(m_pre_2_9p, t));
237  }
238  }
239  const Integer Y = W + q * modp.Multiply(m_pre_q_p, (X - W));
240 
241  // Signature
242  Integer s = modn.Multiply(modn.Square(Y), rInv);
243  CRYPTOPP_ASSERT((e * f * s.Squared()) % m_n == x);
244 
245  // IEEE P1363, Section 8.2.8 IFSP-RW, p.44
246  s = STDMIN(s, m_n - s);
247  if (ApplyFunction(s) != x) // check
248  throw Exception(Exception::OTHER_ERROR, "InvertibleRWFunction: computational error during private key operation");
249 
250  return s;
251 }
252 
253 bool InvertibleRWFunction::Validate(RandomNumberGenerator &rng, unsigned int level) const
254 {
255  bool pass = RWFunction::Validate(rng, level);
256  CRYPTOPP_ASSERT(pass);
257  pass = pass && m_p > Integer::One() && m_p%8 == 3 && m_p < m_n;
258  CRYPTOPP_ASSERT(pass);
259  pass = pass && m_q > Integer::One() && m_q%8 == 7 && m_q < m_n;
260  CRYPTOPP_ASSERT(pass);
261  pass = pass && m_u.IsPositive() && m_u < m_p;
262  CRYPTOPP_ASSERT(pass);
263  if (level >= 1)
264  {
265  pass = pass && m_p * m_q == m_n;
266  CRYPTOPP_ASSERT(pass);
267  pass = pass && m_u * m_q % m_p == 1;
268  CRYPTOPP_ASSERT(pass);
269  }
270  if (level >= 2)
271  {
272  pass = pass && VerifyPrime(rng, m_p, level-2) && VerifyPrime(rng, m_q, level-2);
273  CRYPTOPP_ASSERT(pass);
274  }
275  return pass;
276 }
277 
278 bool InvertibleRWFunction::GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
279 {
280  return GetValueHelper<RWFunction>(this, name, valueType, pValue).Assignable()
281  CRYPTOPP_GET_FUNCTION_ENTRY(Prime1)
282  CRYPTOPP_GET_FUNCTION_ENTRY(Prime2)
283  CRYPTOPP_GET_FUNCTION_ENTRY(MultiplicativeInverseOfPrime2ModPrime1)
284  ;
285 }
286 
288 {
289  AssignFromHelper<RWFunction>(this, source)
290  CRYPTOPP_SET_FUNCTION_ENTRY(Prime1)
291  CRYPTOPP_SET_FUNCTION_ENTRY(Prime2)
292  CRYPTOPP_SET_FUNCTION_ENTRY(MultiplicativeInverseOfPrime2ModPrime1)
293  ;
294 
295  m_precompute = false;
296 }
297 
298 NAMESPACE_END
299 
300 #endif
Base class for all exceptions thrown by the library.
Definition: cryptlib.h:158
const char * MultiplicativeInverseOfPrime2ModPrime1()
Integer.
Definition: argnames.h:47
An invalid argument was detected.
Definition: cryptlib.h:202
Integer MultiplicativeInverse() const
Calculate multiplicative inverse.
Definition: integer.cpp:4392
Integer CalculateInverse(RandomNumberGenerator &rng, const Integer &x) const
Calculates the inverse of an element.
Definition: rw.cpp:188
const char * Prime2()
Integer.
Definition: argnames.h:44
bool Validate(RandomNumberGenerator &rng, unsigned int level) const
Check this object for errors.
Definition: rw.cpp:253
void DEREncode(BufferedTransformation &bt) const
Encode in DER format.
Definition: integer.cpp:3432
Some other error occurred not belonging to other categories.
Definition: cryptlib.h:177
void Initialize(const Integer &n, const Integer &p, const Integer &q, const Integer &u)
Initialize a Rabin-Williams private key.
Definition: rw.cpp:118
Ring of congruence classes modulo n.
Definition: modarith.h:38
Interface for random number generators.
Definition: cryptlib.h:1383
void Randomize(RandomNumberGenerator &rng, size_t bitCount)
Set this Integer to random integer.
Definition: integer.cpp:3503
Combines two sets of NameValuePairs.
Definition: algparam.h:124
Integer InverseMod(const Integer &n) const
Calculate multiplicative inverse.
Definition: integer.cpp:4421
BER Sequence Decoder.
Definition: asn.h:309
void GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &params=g_nullNameValuePairs)
Generate a random number.
Definition: integer.h:484
Interface for buffered transformations.
Definition: cryptlib.h:1598
Integer ApplyFunction(const Integer &x) const
Applies the trapdoor.
Definition: rw.cpp:36
bool IsPositive() const
Determines if the Integer is positive.
Definition: integer.h:342
static const Integer & One()
Integer representing 1.
Definition: integer.cpp:4868
void GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &alg)
Definition: rw.cpp:100
bool Validate(RandomNumberGenerator &rng, unsigned int level) const
Check this object for errors.
Definition: rw.cpp:73
const char * Prime1()
Integer.
Definition: argnames.h:43
void DoQuickSanityCheck() const
Perform a quick sanity check.
Definition: cryptlib.h:2387
Classes for Rabin-Williams signature scheme.
bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
Get a named value.
Definition: rw.cpp:278
bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
Get a named value.
Definition: rw.cpp:82
const Integer & Multiply(const Integer &a, const Integer &b) const
Multiplies elements in the ring.
Definition: modarith.h:174
AlgorithmParameters MakeParameters(const char *name, const T &value, bool throwIfNotUsed=true)
Create an object that implements NameValuePairs.
Definition: algparam.h:502
bool IsZero() const
Determines if the Integer is 0.
Definition: integer.h:330
bool VerifyPrime(RandomNumberGenerator &rng, const Integer &p, unsigned int level=1)
Verifies a number is probably prime.
Definition: nbtheory.cpp:247
void Negate()
Reverse the Sign of the Integer.
Definition: integer.cpp:4327
void AssignFrom(const NameValuePairs &source)
Assign values to this object.
Definition: rw.cpp:89
Multiple precision integer with arithmetic operations.
Definition: integer.h:49
Precompiled header file.
virtual Element Exponentiate(const Element &a, const Integer &e) const
Raises a base to an exponent in the group.
Definition: algebra.cpp:316
const T & STDMIN(const T &a, const T &b)
Replacement function for std::min.
Definition: misc.h:535
#define CRYPTOPP_ASSERT(exp)
Debugging and diagnostic assertion.
Definition: trap.h:69
virtual void LoadPrecomputation(BufferedTransformation &storedPrecomputation)
Retrieve previously saved precomputation.
Definition: rw.cpp:142
Classes and functions for working with ANS.1 objects.
Classes and functions for number theoretic operations.
DER Sequence Encoder.
Definition: asn.h:319
Integer Squared() const
Multiply this integer by itself.
Definition: integer.h:609
An object that implements NameValuePairs.
Definition: algparam.h:419
const char * Modulus()
Integer.
Definition: argnames.h:33
virtual void SavePrecomputation(BufferedTransformation &storedPrecomputation) const
Save precomputation for later use.
Definition: rw.cpp:153
Multiple precision integer with arithmetic operations.
static const Integer & Zero()
Integer representing 0.
Definition: integer.cpp:4856
void AssignFrom(const NameValuePairs &source)
Assign values to this object.
Definition: rw.cpp:287
void BERDecode(const byte *input, size_t inputLen)
Decode from BER format.
Definition: integer.cpp:3439
Class file for performing modular arithmetic.
Crypto++ library namespace.
virtual void Precompute(unsigned int unused=0)
Perform precomputation.
Definition: rw.h:110
bool GetIntValue(const char *name, int &value) const
Get a named value with type int.
Definition: cryptlib.h:386
Interface for retrieving values given their names.
Definition: cryptlib.h:293