- Main Page
- Namespaces
- Classes
- Files

# rsa.cpp

    00001 // rsa.cpp - written and placed in the public domain by Wei Dai
    00002
    00003 #include "pch.h"
    00004 #include "rsa.h"
    00005 #include "asn.h"
    00006 #include "oids.h"
    00007 #include "modarith.h"
    00008 #include "nbtheory.h"
    00009 #include "sha.h"
    00010 #include "algparam.h"
    00011 #include "fips140.h"
    00012
    00013 #if !defined(NDEBUG) && !defined(CRYPTOPP_IS_DLL)
    00014 #include "pssr.h"
    00015 NAMESPACE_BEGIN(CryptoPP)
    00016 void RSA_TestInstantiations()
    00017 {
    00018         RSASS<PKCS1v15, SHA>::Verifier x1(1, 1);
    00019         RSASS<PKCS1v15, SHA>::Signer x2(NullRNG(), 1);
    00020         RSASS<PKCS1v15, SHA>::Verifier x3(x2);
    00021         RSASS<PKCS1v15, SHA>::Verifier x4(x2.GetKey());
    00022         RSASS<PSS, SHA>::Verifier x5(x3);
    00023 #ifndef __MWERKS__
    00024         RSASS<PSSR, SHA>::Signer x6 = x2;
    00025         x3 = x2;
    00026         x6 = x2;
    00027 #endif
    00028         RSAES<PKCS1v15>::Encryptor x7(x2);
    00029 #ifndef __GNUC__
    00030         RSAES<PKCS1v15>::Encryptor x8(x3);
    00031 #endif
    00032         RSAES<OAEP<SHA> >::Encryptor x9(x2);
    00033
    00034         x4 = x2.GetKey();
    00035 }
    00036 NAMESPACE_END
    00037 #endif
    00038
    00039 #ifndef CRYPTOPP_IMPORTS
    00040
    00041 NAMESPACE_BEGIN(CryptoPP)
    00042
    00043 OID RSAFunction::GetAlgorithmID() const
    00044 {
    00045         return ASN1::rsaEncryption();
    00046 }
    00047
    00048 void RSAFunction::BERDecodePublicKey(BufferedTransformation &bt, bool, size_t)
    00049 {
    00050         BERSequenceDecoder seq(bt);
    00051                 m_n.BERDecode(seq);
    00052                 m_e.BERDecode(seq);
    00053         seq.MessageEnd();
    00054 }
    00055
    00056 void RSAFunction::DEREncodePublicKey(BufferedTransformation &bt) const
    00057 {
    00058         DERSequenceEncoder seq(bt);
    00059                 m_n.DEREncode(seq);
    00060                 m_e.DEREncode(seq);
    00061         seq.MessageEnd();
    00062 }
    00063
    00064 Integer RSAFunction::ApplyFunction(const Integer &x) const
    00065 {
    00066         DoQuickSanityCheck();
    00067         return a_exp_b_mod_c(x, m_e, m_n);
    00068 }
    00069
    00070 bool RSAFunction::Validate(RandomNumberGenerator &rng, unsigned int level) const
    00071 {
    00072         bool pass = true;
    00073         pass = pass && m_n > Integer::One() && m_n.IsOdd();
    00074         pass = pass && m_e > Integer::One() && m_e.IsOdd() && m_e < m_n;
    00075         return pass;
    00076 }
    00077
    00078 bool RSAFunction::GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
    00079 {
    00080         return GetValueHelper(this, name, valueType, pValue).Assignable()
    00081                 CRYPTOPP_GET_FUNCTION_ENTRY(Modulus)
    00082                 CRYPTOPP_GET_FUNCTION_ENTRY(PublicExponent)
    00083                 ;
    00084 }
    00085
    00086 void RSAFunction::AssignFrom(const NameValuePairs &source)
    00087 {
    00088         AssignFromHelper(this, source)
    00089                 CRYPTOPP_SET_FUNCTION_ENTRY(Modulus)
    00090                 CRYPTOPP_SET_FUNCTION_ENTRY(PublicExponent)
    00091                 ;
    00092 }
    00093
    00094 // *****************************************************************************
    00095
    00096 class RSAPrimeSelector : public PrimeSelector
    00097 {
    00098 public:
    00099         RSAPrimeSelector(const Integer &e) : m_e(e) {}
    00100         bool IsAcceptable(const Integer &candidate) const {return RelativelyPrime(m_e, candidate-Integer::One());}
    00101         Integer m_e;
    00102 };
    00103
    00104 void InvertibleRSAFunction::GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &alg)
    00105 {
    00106         int modulusSize = 2048;
    00107         alg.GetIntValue(Name::ModulusSize(), modulusSize) || alg.GetIntValue(Name::KeySize(), modulusSize);
    00108
    00109         if (modulusSize < 16)
    00110                 throw InvalidArgument("InvertibleRSAFunction: specified modulus size is too small");
    00111
    00112         m_e = alg.GetValueWithDefault(Name::PublicExponent(), Integer(17));
    00113
    00114         if (m_e < 3 || m_e.IsEven())
    00115                 throw InvalidArgument("InvertibleRSAFunction: invalid public exponent");
    00116
    00117         RSAPrimeSelector selector(m_e);
    00118         AlgorithmParameters primeParam = MakeParametersForTwoPrimesOfEqualSize(modulusSize)
    00119                 (Name::PointerToPrimeSelector(), selector.GetSelectorPointer());
    00120         m_p.GenerateRandom(rng, primeParam);
    00121         m_q.GenerateRandom(rng, primeParam);
    00122
    00123         m_d = m_e.InverseMod(LCM(m_p-1, m_q-1));
    00124         assert(m_d.IsPositive());
    00125
    00126         m_dp = m_d % (m_p-1);
    00127         m_dq = m_d % (m_q-1);
    00128         m_n = m_p * m_q;
    00129         m_u = m_q.InverseMod(m_p);
    00130
    00131         if (FIPS_140_2_ComplianceEnabled())
    00132         {
    00133                 RSASS<PKCS1v15, SHA>::Signer signer(*this);
    00134                 RSASS<PKCS1v15, SHA>::Verifier verifier(signer);
    00135                 SignaturePairwiseConsistencyTest_FIPS_140_Only(signer, verifier);
    00136
    00137                 RSAES<OAEP<SHA> >::Decryptor decryptor(*this);
    00138                 RSAES<OAEP<SHA> >::Encryptor encryptor(decryptor);
    00139                 EncryptionPairwiseConsistencyTest_FIPS_140_Only(encryptor, decryptor);
    00140         }
    00141 }
    00142
    00143 void InvertibleRSAFunction::Initialize(RandomNumberGenerator &rng, unsigned int keybits, const Integer &e)
    00144 {
    00145         GenerateRandom(rng, MakeParameters(Name::ModulusSize(), (int)keybits)(Name::PublicExponent(), e+e.IsEven()));
    00146 }
    00147
    00148 void InvertibleRSAFunction::Initialize(const Integer &n, const Integer &e, const Integer &d)
    00149 {
    00150         if (n.IsEven() || e.IsEven() | d.IsEven())
    00151                 throw InvalidArgument("InvertibleRSAFunction: input is not a valid RSA private key");
    00152
    00153         m_n = n;
    00154         m_e = e;
    00155         m_d = d;
    00156
    00157         Integer r = --(d*e);
    00158         unsigned int s = 0;
    00159         while (r.IsEven())
    00160         {
    00161                 r >>= 1;
    00162                 s++;
    00163         }
    00164
    00165         ModularArithmetic modn(n);
    00166         for (Integer i = 2; ; ++i)
    00167         {
    00168                 Integer a = modn.Exponentiate(i, r);
    00169                 if (a == 1)
    00170                         continue;
    00171                 Integer b;
    00172                 unsigned int j = 0;
    00173                 while (a != n-1)
    00174                 {
    00175                         b = modn.Square(a);
    00176                         if (b == 1)
    00177                         {
    00178                                 m_p = GCD(a-1, n);
    00179                                 m_q = n/m_p;
    00180                                 m_dp = m_d % (m_p-1);
    00181                                 m_dq = m_d % (m_q-1);
    00182                                 m_u = m_q.InverseMod(m_p);
    00183                                 return;
    00184                         }
    00185                         if (++j == s)
    00186                                 throw InvalidArgument("InvertibleRSAFunction: input is not a valid RSA private key");
    00187                         a = b;
    00188                 }
    00189         }
    00190 }
    00191
    00192 void InvertibleRSAFunction::BERDecodePrivateKey(BufferedTransformation &bt, bool, size_t)
    00193 {
    00194         BERSequenceDecoder privateKey(bt);
    00195                 word32 version;
    00196                 BERDecodeUnsigned<word32>(privateKey, version, INTEGER, 0, 0);  // check version
    00197                 m_n.BERDecode(privateKey);
    00198                 m_e.BERDecode(privateKey);
    00199                 m_d.BERDecode(privateKey);
    00200                 m_p.BERDecode(privateKey);
    00201                 m_q.BERDecode(privateKey);
    00202                 m_dp.BERDecode(privateKey);
    00203                 m_dq.BERDecode(privateKey);
    00204                 m_u.BERDecode(privateKey);
    00205         privateKey.MessageEnd();
    00206 }
    00207
    00208 void InvertibleRSAFunction::DEREncodePrivateKey(BufferedTransformation &bt) const
    00209 {
    00210         DERSequenceEncoder privateKey(bt);
    00211                 DEREncodeUnsigned<word32>(privateKey, 0);       // version
    00212                 m_n.DEREncode(privateKey);
    00213                 m_e.DEREncode(privateKey);
    00214                 m_d.DEREncode(privateKey);
    00215                 m_p.DEREncode(privateKey);
    00216                 m_q.DEREncode(privateKey);
    00217                 m_dp.DEREncode(privateKey);
    00218                 m_dq.DEREncode(privateKey);
    00219                 m_u.DEREncode(privateKey);
    00220         privateKey.MessageEnd();
    00221 }
    00222
    00223 Integer InvertibleRSAFunction::CalculateInverse(RandomNumberGenerator &rng, const Integer &x) const
    00224 {
    00225         DoQuickSanityCheck();
    00226         ModularArithmetic modn(m_n);
    00227         Integer r, rInv;
    00228         do {    // do this in a loop for people using small numbers for testing
    00229                 r.Randomize(rng, Integer::One(), m_n - Integer::One());
    00230                 rInv = modn.MultiplicativeInverse(r);
    00231         } while (rInv.IsZero());
    00232         Integer re = modn.Exponentiate(r, m_e);
    00233         re = modn.Multiply(re, x);                      // blind
    00234         // here we follow the notation of PKCS #1 and let u=q inverse mod p
    00235         // but in ModRoot, u=p inverse mod q, so we reverse the order of p and q
    00236         Integer y = ModularRoot(re, m_dq, m_dp, m_q, m_p, m_u);
    00237         y = modn.Multiply(y, rInv);                             // unblind
    00238         if (modn.Exponentiate(y, m_e) != x)             // check
    00239                 throw Exception(Exception::OTHER_ERROR, "InvertibleRSAFunction: computational error during private key operation");
    00240         return y;
    00241 }
    00242
    00243 bool InvertibleRSAFunction::Validate(RandomNumberGenerator &rng, unsigned int level) const
    00244 {
    00245         bool pass = RSAFunction::Validate(rng, level);
    00246         pass = pass && m_p > Integer::One() && m_p.IsOdd() && m_p < m_n;
    00247         pass = pass && m_q > Integer::One() && m_q.IsOdd() && m_q < m_n;
    00248         pass = pass && m_d > Integer::One() && m_d.IsOdd() && m_d < m_n;
    00249         pass = pass && m_dp > Integer::One() && m_dp.IsOdd() && m_dp < m_p;
    00250         pass = pass && m_dq > Integer::One() && m_dq.IsOdd() && m_dq < m_q;
    00251         pass = pass && m_u.IsPositive() && m_u < m_p;
    00252         if (level >= 1)
    00253         {
    00254                 pass = pass && m_p * m_q == m_n;
    00255                 pass = pass && m_e*m_d % LCM(m_p-1, m_q-1) == 1;
    00256                 pass = pass && m_dp == m_d%(m_p-1) && m_dq == m_d%(m_q-1);
    00257                 pass = pass && m_u * m_q % m_p == 1;
    00258         }
    00259         if (level >= 2)
    00260                 pass = pass && VerifyPrime(rng, m_p, level-2) && VerifyPrime(rng, m_q, level-2);
    00261         return pass;
    00262 }
    00263
    00264 bool InvertibleRSAFunction::GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
    00265 {
    00266         return GetValueHelper<RSAFunction>(this, name, valueType, pValue).Assignable()
    00267                 CRYPTOPP_GET_FUNCTION_ENTRY(Prime1)
    00268                 CRYPTOPP_GET_FUNCTION_ENTRY(Prime2)
    00269                 CRYPTOPP_GET_FUNCTION_ENTRY(PrivateExponent)
    00270                 CRYPTOPP_GET_FUNCTION_ENTRY(ModPrime1PrivateExponent)
    00271                 CRYPTOPP_GET_FUNCTION_ENTRY(ModPrime2PrivateExponent)
    00272                 CRYPTOPP_GET_FUNCTION_ENTRY(MultiplicativeInverseOfPrime2ModPrime1)
    00273                 ;
    00274 }
    00275
    00276 void InvertibleRSAFunction::AssignFrom(const NameValuePairs &source)
    00277 {
    00278         AssignFromHelper<RSAFunction>(this, source)
    00279                 CRYPTOPP_SET_FUNCTION_ENTRY(Prime1)
    00280                 CRYPTOPP_SET_FUNCTION_ENTRY(Prime2)
    00281                 CRYPTOPP_SET_FUNCTION_ENTRY(PrivateExponent)
    00282                 CRYPTOPP_SET_FUNCTION_ENTRY(ModPrime1PrivateExponent)
    00283                 CRYPTOPP_SET_FUNCTION_ENTRY(ModPrime2PrivateExponent)
    00284                 CRYPTOPP_SET_FUNCTION_ENTRY(MultiplicativeInverseOfPrime2ModPrime1)
    00285                 ;
    00286 }
    00287
    00288 // *****************************************************************************
    00289
    00290 Integer RSAFunction_ISO::ApplyFunction(const Integer &x) const
    00291 {
    00292         Integer t = RSAFunction::ApplyFunction(x);
    00293         return t % 16 == 12 ? t : m_n - t;
    00294 }
    00295
    00296 Integer InvertibleRSAFunction_ISO::CalculateInverse(RandomNumberGenerator &rng, const Integer &x) const
    00297 {
    00298         Integer t = InvertibleRSAFunction::CalculateInverse(rng, x);
    00299         return STDMIN(t, m_n-t);
    00300 }
    00301
    00302 NAMESPACE_END
    00303
    00304 #endif