Crypto++  5.6.5
Free C++ class library of cryptographic schemes
rsa.cpp
1 // rsa.cpp - originally written and placed in the public domain by Wei Dai
2 
3 #include "pch.h"
4 #include "rsa.h"
5 #include "asn.h"
6 #include "sha.h"
7 #include "oids.h"
8 #include "modarith.h"
9 #include "nbtheory.h"
10 #include "algparam.h"
11 #include "fips140.h"
12 
13 #if defined(CRYPTOPP_DEBUG) && !defined(CRYPTOPP_DOXYGEN_PROCESSING) && !defined(CRYPTOPP_IS_DLL)
14 #include "pssr.h"
15 NAMESPACE_BEGIN(CryptoPP)
16 void RSA_TestInstantiations()
17 {
21  RSASS<PKCS1v15, SHA>::Verifier x4(x2.GetKey());
23 #ifndef __MWERKS__
25  x3 = x2;
26  x6 = x2;
27 #endif
29 #ifndef __GNUC__
31 #endif
32  RSAES<OAEP<SHA> >::Encryptor x9(x2);
33 
34  x4 = x2.GetKey();
35 }
36 NAMESPACE_END
37 #endif
38 
39 #ifndef CRYPTOPP_IMPORTS
40 
41 NAMESPACE_BEGIN(CryptoPP)
42 
43 OID RSAFunction::GetAlgorithmID() const
44 {
45  return ASN1::rsaEncryption();
46 }
47 
49 {
50  BERSequenceDecoder seq(bt);
51  m_n.BERDecode(seq);
52  m_e.BERDecode(seq);
53  seq.MessageEnd();
54 }
55 
57 {
58  DERSequenceEncoder seq(bt);
59  m_n.DEREncode(seq);
60  m_e.DEREncode(seq);
61  seq.MessageEnd();
62 }
63 
65 {
67  return a_exp_b_mod_c(x, m_e, m_n);
68 }
69 
70 bool RSAFunction::Validate(RandomNumberGenerator& rng, unsigned int level) const
71 {
72  CRYPTOPP_UNUSED(rng), CRYPTOPP_UNUSED(level);
73 
74  bool pass = true;
75  pass = pass && m_n > Integer::One() && m_n.IsOdd();
76  CRYPTOPP_ASSERT(pass);
77  pass = pass && m_e > Integer::One() && m_e.IsOdd() && m_e < m_n;
78  CRYPTOPP_ASSERT(pass);
79  return pass;
80 }
81 
82 bool RSAFunction::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  CRYPTOPP_GET_FUNCTION_ENTRY(PublicExponent)
87  ;
88 }
89 
91 {
92  AssignFromHelper(this, source)
93  CRYPTOPP_SET_FUNCTION_ENTRY(Modulus)
94  CRYPTOPP_SET_FUNCTION_ENTRY(PublicExponent)
95  ;
96 }
97 
98 // *****************************************************************************
99 
101 {
102 public:
103  RSAPrimeSelector(const Integer &e) : m_e(e) {}
104  bool IsAcceptable(const Integer &candidate) const {return RelativelyPrime(m_e, candidate-Integer::One());}
105  Integer m_e;
106 };
107 
109 {
110  int modulusSize = 2048;
111  alg.GetIntValue(Name::ModulusSize(), modulusSize) || alg.GetIntValue(Name::KeySize(), modulusSize);
112 
113  CRYPTOPP_ASSERT(modulusSize >= 16);
114  if (modulusSize < 16)
115  throw InvalidArgument("InvertibleRSAFunction: specified modulus size is too small");
116 
118 
119  CRYPTOPP_ASSERT(m_e >= 3); CRYPTOPP_ASSERT(!m_e.IsEven());
120  if (m_e < 3 || m_e.IsEven())
121  throw InvalidArgument("InvertibleRSAFunction: invalid public exponent");
122 
123  RSAPrimeSelector selector(m_e);
124  AlgorithmParameters primeParam = MakeParametersForTwoPrimesOfEqualSize(modulusSize)
125  (Name::PointerToPrimeSelector(), selector.GetSelectorPointer());
126  m_p.GenerateRandom(rng, primeParam);
127  m_q.GenerateRandom(rng, primeParam);
128 
129  m_d = m_e.InverseMod(LCM(m_p-1, m_q-1));
130  CRYPTOPP_ASSERT(m_d.IsPositive());
131 
132  m_dp = m_d % (m_p-1);
133  m_dq = m_d % (m_q-1);
134  m_n = m_p * m_q;
135  m_u = m_q.InverseMod(m_p);
136 
138  {
139  RSASS<PKCS1v15, SHA>::Signer signer(*this);
140  RSASS<PKCS1v15, SHA>::Verifier verifier(signer);
141  SignaturePairwiseConsistencyTest_FIPS_140_Only(signer, verifier);
142 
143  RSAES<OAEP<SHA> >::Decryptor decryptor(*this);
144  RSAES<OAEP<SHA> >::Encryptor encryptor(decryptor);
145  EncryptionPairwiseConsistencyTest_FIPS_140_Only(encryptor, decryptor);
146  }
147 }
148 
149 void InvertibleRSAFunction::Initialize(RandomNumberGenerator &rng, unsigned int keybits, const Integer &e)
150 {
151  GenerateRandom(rng, MakeParameters(Name::ModulusSize(), (int)keybits)(Name::PublicExponent(), e+e.IsEven()));
152 }
153 
154 void InvertibleRSAFunction::Initialize(const Integer &n, const Integer &e, const Integer &d)
155 {
156  if (n.IsEven() || e.IsEven() | d.IsEven())
157  throw InvalidArgument("InvertibleRSAFunction: input is not a valid RSA private key");
158 
159  m_n = n;
160  m_e = e;
161  m_d = d;
162 
163  Integer r = --(d*e);
164  unsigned int s = 0;
165  while (r.IsEven())
166  {
167  r >>= 1;
168  s++;
169  }
170 
171  ModularArithmetic modn(n);
172  for (Integer i = 2; ; ++i)
173  {
174  Integer a = modn.Exponentiate(i, r);
175  if (a == 1)
176  continue;
177  Integer b;
178  unsigned int j = 0;
179  while (a != n-1)
180  {
181  b = modn.Square(a);
182  if (b == 1)
183  {
184  m_p = GCD(a-1, n);
185  m_q = n/m_p;
186  m_dp = m_d % (m_p-1);
187  m_dq = m_d % (m_q-1);
188  m_u = m_q.InverseMod(m_p);
189  return;
190  }
191  if (++j == s)
192  throw InvalidArgument("InvertibleRSAFunction: input is not a valid RSA private key");
193  a = b;
194  }
195  }
196 }
197 
199 {
200  BERSequenceDecoder privateKey(bt);
201  word32 version;
202  BERDecodeUnsigned<word32>(privateKey, version, INTEGER, 0, 0); // check version
203  m_n.BERDecode(privateKey);
204  m_e.BERDecode(privateKey);
205  m_d.BERDecode(privateKey);
206  m_p.BERDecode(privateKey);
207  m_q.BERDecode(privateKey);
208  m_dp.BERDecode(privateKey);
209  m_dq.BERDecode(privateKey);
210  m_u.BERDecode(privateKey);
211  privateKey.MessageEnd();
212 }
213 
215 {
216  DERSequenceEncoder privateKey(bt);
217  DEREncodeUnsigned<word32>(privateKey, 0); // version
218  m_n.DEREncode(privateKey);
219  m_e.DEREncode(privateKey);
220  m_d.DEREncode(privateKey);
221  m_p.DEREncode(privateKey);
222  m_q.DEREncode(privateKey);
223  m_dp.DEREncode(privateKey);
224  m_dq.DEREncode(privateKey);
225  m_u.DEREncode(privateKey);
226  privateKey.MessageEnd();
227 }
228 
230 {
232  ModularArithmetic modn(m_n);
233  Integer r, rInv;
234  do { // do this in a loop for people using small numbers for testing
235  r.Randomize(rng, Integer::One(), m_n - Integer::One());
236  rInv = modn.MultiplicativeInverse(r);
237  } while (rInv.IsZero());
238  Integer re = modn.Exponentiate(r, m_e);
239  re = modn.Multiply(re, x); // blind
240  // here we follow the notation of PKCS #1 and let u=q inverse mod p
241  // but in ModRoot, u=p inverse mod q, so we reverse the order of p and q
242  Integer y = ModularRoot(re, m_dq, m_dp, m_q, m_p, m_u);
243  y = modn.Multiply(y, rInv); // unblind
244  if (modn.Exponentiate(y, m_e) != x) // check
245  throw Exception(Exception::OTHER_ERROR, "InvertibleRSAFunction: computational error during private key operation");
246  return y;
247 }
248 
249 bool InvertibleRSAFunction::Validate(RandomNumberGenerator &rng, unsigned int level) const
250 {
251  bool pass = RSAFunction::Validate(rng, level);
252  CRYPTOPP_ASSERT(pass);
253  pass = pass && m_p > Integer::One() && m_p.IsOdd() && m_p < m_n;
254  CRYPTOPP_ASSERT(pass);
255  pass = pass && m_q > Integer::One() && m_q.IsOdd() && m_q < m_n;
256  CRYPTOPP_ASSERT(pass);
257  pass = pass && m_d > Integer::One() && m_d.IsOdd() && m_d < m_n;
258  CRYPTOPP_ASSERT(pass);
259  pass = pass && m_dp > Integer::One() && m_dp.IsOdd() && m_dp < m_p;
260  CRYPTOPP_ASSERT(pass);
261  pass = pass && m_dq > Integer::One() && m_dq.IsOdd() && m_dq < m_q;
262  CRYPTOPP_ASSERT(pass);
263  pass = pass && m_u.IsPositive() && m_u < m_p;
264  CRYPTOPP_ASSERT(pass);
265  if (level >= 1)
266  {
267  pass = pass && m_p * m_q == m_n;
268  CRYPTOPP_ASSERT(pass);
269  pass = pass && m_e*m_d % LCM(m_p-1, m_q-1) == 1;
270  CRYPTOPP_ASSERT(pass);
271  pass = pass && m_dp == m_d%(m_p-1) && m_dq == m_d%(m_q-1);
272  CRYPTOPP_ASSERT(pass);
273  pass = pass && m_u * m_q % m_p == 1;
274  CRYPTOPP_ASSERT(pass);
275  }
276  if (level >= 2)
277  {
278  pass = pass && VerifyPrime(rng, m_p, level-2) && VerifyPrime(rng, m_q, level-2);
279  CRYPTOPP_ASSERT(pass);
280  }
281  return pass;
282 }
283 
284 bool InvertibleRSAFunction::GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
285 {
286  return GetValueHelper<RSAFunction>(this, name, valueType, pValue).Assignable()
287  CRYPTOPP_GET_FUNCTION_ENTRY(Prime1)
288  CRYPTOPP_GET_FUNCTION_ENTRY(Prime2)
289  CRYPTOPP_GET_FUNCTION_ENTRY(PrivateExponent)
290  CRYPTOPP_GET_FUNCTION_ENTRY(ModPrime1PrivateExponent)
291  CRYPTOPP_GET_FUNCTION_ENTRY(ModPrime2PrivateExponent)
292  CRYPTOPP_GET_FUNCTION_ENTRY(MultiplicativeInverseOfPrime2ModPrime1)
293  ;
294 }
295 
297 {
298  AssignFromHelper<RSAFunction>(this, source)
299  CRYPTOPP_SET_FUNCTION_ENTRY(Prime1)
300  CRYPTOPP_SET_FUNCTION_ENTRY(Prime2)
301  CRYPTOPP_SET_FUNCTION_ENTRY(PrivateExponent)
302  CRYPTOPP_SET_FUNCTION_ENTRY(ModPrime1PrivateExponent)
303  CRYPTOPP_SET_FUNCTION_ENTRY(ModPrime2PrivateExponent)
304  CRYPTOPP_SET_FUNCTION_ENTRY(MultiplicativeInverseOfPrime2ModPrime1)
305  ;
306 }
307 
308 // *****************************************************************************
309 
311 {
313  return t % 16 == 12 ? t : m_n - t;
314 }
315 
317 {
319  return STDMIN(t, m_n-t);
320 }
321 
322 NAMESPACE_END
323 
324 #endif
Base class for all exceptions thrown by the library.
Definition: cryptlib.h:150
const char * MultiplicativeInverseOfPrime2ModPrime1()
Integer.
Definition: argnames.h:47
An invalid argument was detected.
Definition: cryptlib.h:194
Classes for working with NameValuePairs.
const Integer & Square(const Integer &a) const
Square an element in the ring.
Definition: modarith.h:177
const char * Prime2()
Integer.
Definition: argnames.h:44
T GetValueWithDefault(const char *name, T defaultValue) const
Get a named value.
Definition: cryptlib.h:356
void DEREncode(BufferedTransformation &bt) const
Encode in DER format.
Definition: integer.cpp:3457
void BERDecodePrivateKey(BufferedTransformation &bt, bool parametersPresent, size_t size)
decode privateKey part of privateKeyInfo, without the OCTET STRING header
Definition: rsa.cpp:198
void GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &alg)
Generate a random key or crypto parameters.
Definition: rsa.cpp:108
bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
Get a named value.
Definition: rsa.cpp:284
const Integer & MultiplicativeInverse(const Integer &a) const
Calculate the multiplicative inverse of an element in the ring.
Definition: modarith.h:190
Some other error occurred not belonging to other categories.
Definition: cryptlib.h:169
ASN.1 object identifiers for algorthms and schemes.
Ring of congruence classes modulo n.
Definition: modarith.h:34
Interface for random number generators.
Definition: cryptlib.h:1190
void Randomize(RandomNumberGenerator &rng, size_t bitCount)
Set this Integer to random integer.
Definition: integer.cpp:3528
Integer InverseMod(const Integer &n) const
calculate multiplicative inverse of *this mod n
Definition: integer.cpp:4440
bool Validate(RandomNumberGenerator &rng, unsigned int level) const
Check this object for errors.
Definition: rsa.cpp:249
BER Sequence Decoder.
Definition: asn.h:303
Interface for buffered transformations.
Definition: cryptlib.h:1345
static const Integer & One()
Integer representing 1.
Definition: integer.cpp:3096
void BERDecodePublicKey(BufferedTransformation &bt, bool parametersPresent, size_t size)
decode subjectPublicKey part of subjectPublicKeyInfo, without the BIT STRING header ...
Definition: rsa.cpp:48
const char * PrivateExponent()
Integer.
Definition: argnames.h:35
Integer ApplyFunction(const Integer &x) const
Applies the trapdoor.
Definition: rsa.cpp:64
bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
Get a named value.
Definition: rsa.cpp:82
const char * Prime1()
Integer.
Definition: argnames.h:43
void DoQuickSanityCheck() const
Perform a quick sanity check.
Definition: cryptlib.h:2126
bool FIPS_140_2_ComplianceEnabled()
Determines whether the library provides FIPS validated cryptography.
Definition: fips140.cpp:29
void Initialize(RandomNumberGenerator &rng, unsigned int modulusBits, const Integer &e=17)
Create a RSA private key.
Definition: rsa.cpp:149
const Integer & Multiply(const Integer &a, const Integer &b) const
Multiplies elements in the ring.
Definition: modarith.h:170
AlgorithmParameters MakeParameters(const char *name, const T &value, bool throwIfNotUsed=true)
Create an object that implements NameValuePairs.
Definition: algparam.h:502
const char * PublicExponent()
Integer.
Definition: argnames.h:34
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 prime number.
Definition: nbtheory.cpp:249
void AssignFrom(const NameValuePairs &source)
Assign values to this object.
Definition: rsa.cpp:90
const char * ModPrime1PrivateExponent()
Integer.
Definition: argnames.h:45
Application callback to signal suitability of a cabdidate prime.
Definition: nbtheory.h:80
Multiple precision integer with arithmetic operations.
Definition: integer.h:49
virtual Element Exponentiate(const Element &a, const Integer &e) const
Raises a base to an exponent in the group.
Definition: algebra.cpp:316
const char * ModPrime2PrivateExponent()
Integer.
Definition: argnames.h:46
void AssignFrom(const NameValuePairs &source)
Assign values to this object.
Definition: rsa.cpp:296
Integer CalculateInverse(RandomNumberGenerator &rng, const Integer &x) const
Calculates the inverse of an element.
Definition: rsa.cpp:229
bool IsEven() const
Determines if the Integer is even parity.
Definition: integer.h:348
RandomNumberGenerator & NullRNG()
Random Number Generator that does not produce random numbers.
Definition: cryptlib.cpp:376
const T & STDMIN(const T &a, const T &b)
Replacement function for std::min.
Definition: misc.h:514
#define CRYPTOPP_ASSERT(exp)
Debugging and diagnostic assertion.
Definition: trap.h:61
Classes and functions for working with ANS.1 objects.
Classes for SHA-1 and SHA-2 family of message digests.
const char * PointerToPrimeSelector()
const PrimeSelector *
Definition: argnames.h:42
Classes and functions for number theoretic operations.
const char * KeySize()
int, in bits
Definition: argnames.h:29
DER Sequence Encoder.
Definition: asn.h:313
Classes for the RSA cryptosystem.
bool Validate(RandomNumberGenerator &rng, unsigned int level) const
Check this object for errors.
Definition: rsa.cpp:70
Classes and functions for the FIPS 140-2 validated library.
Integer CalculateInverse(RandomNumberGenerator &rng, const Integer &x) const
Calculates the inverse of an element.
Definition: rsa.cpp:316
An object that implements NameValuePairs.
Definition: algparam.h:437
const char * Modulus()
Integer.
Definition: argnames.h:33
RSA encryption algorithm.
Definition: rsa.h:178
Integer ApplyFunction(const Integer &x) const
Applies the trapdoor.
Definition: rsa.cpp:310
void BERDecode(const byte *input, size_t inputLen)
Decode from BER format.
Definition: integer.cpp:3464
Class file for performing modular arithmetic.
Crypto++ library namespace.
const char * ModulusSize()
int, in bits
Definition: argnames.h:30
bool GetIntValue(const char *name, int &value) const
Get a named value with type int.
Definition: cryptlib.h:379
void DEREncodePublicKey(BufferedTransformation &bt) const
encode subjectPublicKey part of subjectPublicKeyInfo, without the BIT STRING header ...
Definition: rsa.cpp:56
Object Identifier.
Definition: asn.h:166
Classes for probablistic signature schemes.
void DEREncodePrivateKey(BufferedTransformation &bt) const
encode privateKey part of privateKeyInfo, without the OCTET STRING header
Definition: rsa.cpp:214
RSA trapdoor function using the public key.
Definition: rsa.h:24
bool IsOdd() const
Determines if the Integer is odd parity.
Definition: integer.h:351
Interface for retrieving values given their names.
Definition: cryptlib.h:285
Template implementing constructors for public key algorithm classes.
Definition: pubkey.h:1989