Crypto++  8.8
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 
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
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 
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 
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).
196 {
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 
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
AlgorithmParameters MakeParameters(const char *name, const T &value, bool throwIfNotUsed=true)
Create an object that implements NameValuePairs.
Definition: algparam.h:508
Classes and functions for working with ANS.1 objects.
An object that implements NameValuePairs.
Definition: algparam.h:426
BER Sequence Decoder.
Definition: asn.h:525
Interface for buffered transformations.
Definition: cryptlib.h:1657
Combines two sets of NameValuePairs.
Definition: algparam.h:129
void DoQuickSanityCheck() const
Perform a quick sanity check.
Definition: cryptlib.h:2498
DER Sequence Encoder.
Definition: asn.h:557
Base class for all exceptions thrown by the library.
Definition: cryptlib.h:164
@ OTHER_ERROR
Some other error occurred not belonging to other categories.
Definition: cryptlib.h:182
Multiple precision integer with arithmetic operations.
Definition: integer.h:50
void DEREncode(BufferedTransformation &bt) const
Encode in DER format.
void GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &params=g_nullNameValuePairs)
Generate a random number.
Definition: integer.h:509
bool IsPositive() const
Determines if the Integer is positive.
Definition: integer.h:347
void Randomize(RandomNumberGenerator &rng, size_t bitCount)
Set this Integer to random integer.
Integer Squared() const
Multiply this integer by itself.
Definition: integer.h:634
void BERDecode(const byte *input, size_t inputLen)
Decode from BER format.
static const Integer & One()
Integer representing 1.
void Negate()
Reverse the Sign of the Integer.
static const Integer & Zero()
Integer representing 0.
bool IsZero() const
Determines if the Integer is 0.
Definition: integer.h:335
Integer MultiplicativeInverse() const
Calculate multiplicative inverse.
Integer InverseMod(const Integer &n) const
Calculate multiplicative inverse.
An invalid argument was detected.
Definition: cryptlib.h:208
virtual void LoadPrecomputation(BufferedTransformation &storedPrecomputation)
Retrieve previously saved precomputation.
bool Validate(RandomNumberGenerator &rng, unsigned int level) const
Check this object for errors.
void AssignFrom(const NameValuePairs &source)
Assign values to this object.
void Initialize(const Integer &n, const Integer &p, const Integer &q, const Integer &u)
Initialize a Rabin-Williams private key.
virtual void SavePrecomputation(BufferedTransformation &storedPrecomputation) const
Save precomputation for later use.
bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
Get a named value.
void GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &alg)
virtual void Precompute(unsigned int unused=0)
Perform precomputation.
Definition: rw.h:110
Integer CalculateInverse(RandomNumberGenerator &rng, const Integer &x) const
Calculates the inverse of an element.
Ring of congruence classes modulo n.
Definition: modarith.h:44
Interface for retrieving values given their names.
Definition: cryptlib.h:327
CRYPTOPP_DLL bool GetIntValue(const char *name, int &value) const
Get a named value with type int.
Definition: cryptlib.h:420
Integer ApplyFunction(const Integer &x) const
Applies the trapdoor.
void AssignFrom(const NameValuePairs &source)
Assign values to this object.
bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
Get a named value.
bool Validate(RandomNumberGenerator &rng, unsigned int level) const
Check this object for errors.
Interface for random number generators.
Definition: cryptlib.h:1440
word64 word
Full word used for multiprecision integer arithmetic.
Definition: config_int.h:192
Multiple precision integer with arithmetic operations.
const T & STDMIN(const T &a, const T &b)
Replacement function for std::min.
Definition: misc.h:657
Class file for performing modular arithmetic.
Crypto++ library namespace.
const char * Prime1()
Integer.
Definition: argnames.h:43
const char * Modulus()
Integer.
Definition: argnames.h:33
const char * MultiplicativeInverseOfPrime2ModPrime1()
Integer.
Definition: argnames.h:47
const char * Prime2()
Integer.
Definition: argnames.h:44
Classes and functions for number theoretic operations.
CRYPTOPP_DLL bool VerifyPrime(RandomNumberGenerator &rng, const Integer &p, unsigned int level=1)
Verifies a number is probably prime.
Precompiled header file.
Classes for Rabin-Williams signature scheme.
#define CRYPTOPP_ASSERT(exp)
Debugging and diagnostic assertion.
Definition: trap.h:68