Team Fortress 2 Source Code as on 22/4/2020
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

308 lines
8.8 KiB

  1. // rsa.cpp - written and placed in the public domain by Wei Dai
  2. #include "pch.h"
  3. #include "rsa.h"
  4. #include "asn.h"
  5. #include "sha.h"
  6. #include "oids.h"
  7. #include "modarith.h"
  8. #include "nbtheory.h"
  9. #include "algparam.h"
  10. #include "fips140.h"
  11. #if !defined(NDEBUG) && !defined(CRYPTOPP_DOXYGEN_PROCESSING) && !defined(CRYPTOPP_IS_DLL)
  12. #include "pssr.h"
  13. NAMESPACE_BEGIN(CryptoPP)
  14. void RSA_TestInstantiations()
  15. {
  16. RSASS<PKCS1v15, SHA>::Verifier x1(1, 1);
  17. RSASS<PKCS1v15, SHA>::Signer x2(NullRNG(), 1);
  18. RSASS<PKCS1v15, SHA>::Verifier x3(x2);
  19. RSASS<PKCS1v15, SHA>::Verifier x4(x2.GetKey());
  20. RSASS<PSS, SHA>::Verifier x5(x3);
  21. #ifndef __MWERKS__
  22. RSASS<PSSR, SHA>::Signer x6 = x2;
  23. x3 = x2;
  24. x6 = x2;
  25. #endif
  26. RSAES<PKCS1v15>::Encryptor x7(x2);
  27. #ifndef __GNUC__
  28. RSAES<PKCS1v15>::Encryptor x8(x3);
  29. #endif
  30. RSAES<OAEP<SHA> >::Encryptor x9(x2);
  31. x4 = x2.GetKey();
  32. }
  33. NAMESPACE_END
  34. #endif
  35. #ifndef CRYPTOPP_IMPORTS
  36. NAMESPACE_BEGIN(CryptoPP)
  37. OID RSAFunction::GetAlgorithmID() const
  38. {
  39. return ASN1::rsaEncryption();
  40. }
  41. void RSAFunction::BERDecodePublicKey(BufferedTransformation &bt, bool, size_t)
  42. {
  43. BERSequenceDecoder seq(bt);
  44. m_n.BERDecode(seq);
  45. m_e.BERDecode(seq);
  46. seq.MessageEnd();
  47. }
  48. void RSAFunction::DEREncodePublicKey(BufferedTransformation &bt) const
  49. {
  50. DERSequenceEncoder seq(bt);
  51. m_n.DEREncode(seq);
  52. m_e.DEREncode(seq);
  53. seq.MessageEnd();
  54. }
  55. Integer RSAFunction::ApplyFunction(const Integer &x) const
  56. {
  57. DoQuickSanityCheck();
  58. return a_exp_b_mod_c(x, m_e, m_n);
  59. }
  60. bool RSAFunction::Validate(RandomNumberGenerator& rng, unsigned int level) const
  61. {
  62. CRYPTOPP_UNUSED(rng), CRYPTOPP_UNUSED(level);
  63. bool pass = true;
  64. pass = pass && m_n > Integer::One() && m_n.IsOdd();
  65. pass = pass && m_e > Integer::One() && m_e.IsOdd() && m_e < m_n;
  66. return pass;
  67. }
  68. bool RSAFunction::GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
  69. {
  70. return GetValueHelper(this, name, valueType, pValue).Assignable()
  71. CRYPTOPP_GET_FUNCTION_ENTRY(Modulus)
  72. CRYPTOPP_GET_FUNCTION_ENTRY(PublicExponent)
  73. ;
  74. }
  75. void RSAFunction::AssignFrom(const NameValuePairs &source)
  76. {
  77. AssignFromHelper(this, source)
  78. CRYPTOPP_SET_FUNCTION_ENTRY(Modulus)
  79. CRYPTOPP_SET_FUNCTION_ENTRY(PublicExponent)
  80. ;
  81. }
  82. // *****************************************************************************
  83. class RSAPrimeSelector : public PrimeSelector
  84. {
  85. public:
  86. RSAPrimeSelector(const Integer &e) : m_e(e) {}
  87. bool IsAcceptable(const Integer &candidate) const {return RelativelyPrime(m_e, candidate-Integer::One());}
  88. Integer m_e;
  89. };
  90. void InvertibleRSAFunction::GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &alg)
  91. {
  92. int modulusSize = 2048;
  93. alg.GetIntValue(Name::ModulusSize(), modulusSize) || alg.GetIntValue(Name::KeySize(), modulusSize);
  94. assert(modulusSize >= 16);
  95. if (modulusSize < 16)
  96. throw InvalidArgument("InvertibleRSAFunction: specified modulus size is too small");
  97. m_e = alg.GetValueWithDefault(Name::PublicExponent(), Integer(17));
  98. assert(m_e >= 3); assert(!m_e.IsEven());
  99. if (m_e < 3 || m_e.IsEven())
  100. throw InvalidArgument("InvertibleRSAFunction: invalid public exponent");
  101. RSAPrimeSelector selector(m_e);
  102. AlgorithmParameters primeParam = MakeParametersForTwoPrimesOfEqualSize(modulusSize)
  103. (Name::PointerToPrimeSelector(), selector.GetSelectorPointer());
  104. m_p.GenerateRandom(rng, primeParam);
  105. m_q.GenerateRandom(rng, primeParam);
  106. m_d = m_e.InverseMod(LCM(m_p-1, m_q-1));
  107. assert(m_d.IsPositive());
  108. m_dp = m_d % (m_p-1);
  109. m_dq = m_d % (m_q-1);
  110. m_n = m_p * m_q;
  111. m_u = m_q.InverseMod(m_p);
  112. if (FIPS_140_2_ComplianceEnabled())
  113. {
  114. RSASS<PKCS1v15, SHA>::Signer signer(*this);
  115. RSASS<PKCS1v15, SHA>::Verifier verifier(signer);
  116. SignaturePairwiseConsistencyTest_FIPS_140_Only(signer, verifier);
  117. RSAES<OAEP<SHA> >::Decryptor decryptor(*this);
  118. RSAES<OAEP<SHA> >::Encryptor encryptor(decryptor);
  119. EncryptionPairwiseConsistencyTest_FIPS_140_Only(encryptor, decryptor);
  120. }
  121. }
  122. void InvertibleRSAFunction::Initialize(RandomNumberGenerator &rng, unsigned int keybits, const Integer &e)
  123. {
  124. GenerateRandom(rng, MakeParameters(Name::ModulusSize(), (int)keybits)(Name::PublicExponent(), e+e.IsEven()));
  125. }
  126. void InvertibleRSAFunction::Initialize(const Integer &n, const Integer &e, const Integer &d)
  127. {
  128. if (n.IsEven() || e.IsEven() | d.IsEven())
  129. throw InvalidArgument("InvertibleRSAFunction: input is not a valid RSA private key");
  130. m_n = n;
  131. m_e = e;
  132. m_d = d;
  133. Integer r = --(d*e);
  134. unsigned int s = 0;
  135. while (r.IsEven())
  136. {
  137. r >>= 1;
  138. s++;
  139. }
  140. ModularArithmetic modn(n);
  141. for (Integer i = 2; ; ++i)
  142. {
  143. Integer a = modn.Exponentiate(i, r);
  144. if (a == 1)
  145. continue;
  146. Integer b;
  147. unsigned int j = 0;
  148. while (a != n-1)
  149. {
  150. b = modn.Square(a);
  151. if (b == 1)
  152. {
  153. m_p = GCD(a-1, n);
  154. m_q = n/m_p;
  155. m_dp = m_d % (m_p-1);
  156. m_dq = m_d % (m_q-1);
  157. m_u = m_q.InverseMod(m_p);
  158. return;
  159. }
  160. if (++j == s)
  161. throw InvalidArgument("InvertibleRSAFunction: input is not a valid RSA private key");
  162. a = b;
  163. }
  164. }
  165. }
  166. void InvertibleRSAFunction::BERDecodePrivateKey(BufferedTransformation &bt, bool, size_t)
  167. {
  168. BERSequenceDecoder privateKey(bt);
  169. word32 version;
  170. BERDecodeUnsigned<word32>(privateKey, version, INTEGER, 0, 0); // check version
  171. m_n.BERDecode(privateKey);
  172. m_e.BERDecode(privateKey);
  173. m_d.BERDecode(privateKey);
  174. m_p.BERDecode(privateKey);
  175. m_q.BERDecode(privateKey);
  176. m_dp.BERDecode(privateKey);
  177. m_dq.BERDecode(privateKey);
  178. m_u.BERDecode(privateKey);
  179. privateKey.MessageEnd();
  180. }
  181. void InvertibleRSAFunction::DEREncodePrivateKey(BufferedTransformation &bt) const
  182. {
  183. DERSequenceEncoder privateKey(bt);
  184. DEREncodeUnsigned<word32>(privateKey, 0); // version
  185. m_n.DEREncode(privateKey);
  186. m_e.DEREncode(privateKey);
  187. m_d.DEREncode(privateKey);
  188. m_p.DEREncode(privateKey);
  189. m_q.DEREncode(privateKey);
  190. m_dp.DEREncode(privateKey);
  191. m_dq.DEREncode(privateKey);
  192. m_u.DEREncode(privateKey);
  193. privateKey.MessageEnd();
  194. }
  195. Integer InvertibleRSAFunction::CalculateInverse(RandomNumberGenerator &rng, const Integer &x) const
  196. {
  197. DoQuickSanityCheck();
  198. ModularArithmetic modn(m_n);
  199. Integer r, rInv;
  200. do { // do this in a loop for people using small numbers for testing
  201. r.Randomize(rng, Integer::One(), m_n - Integer::One());
  202. rInv = modn.MultiplicativeInverse(r);
  203. } while (rInv.IsZero());
  204. Integer re = modn.Exponentiate(r, m_e);
  205. re = modn.Multiply(re, x); // blind
  206. // here we follow the notation of PKCS #1 and let u=q inverse mod p
  207. // but in ModRoot, u=p inverse mod q, so we reverse the order of p and q
  208. Integer y = ModularRoot(re, m_dq, m_dp, m_q, m_p, m_u);
  209. y = modn.Multiply(y, rInv); // unblind
  210. if (modn.Exponentiate(y, m_e) != x) // check
  211. throw Exception(Exception::OTHER_ERROR, "InvertibleRSAFunction: computational error during private key operation");
  212. return y;
  213. }
  214. bool InvertibleRSAFunction::Validate(RandomNumberGenerator &rng, unsigned int level) const
  215. {
  216. bool pass = RSAFunction::Validate(rng, level);
  217. pass = pass && m_p > Integer::One() && m_p.IsOdd() && m_p < m_n;
  218. pass = pass && m_q > Integer::One() && m_q.IsOdd() && m_q < m_n;
  219. pass = pass && m_d > Integer::One() && m_d.IsOdd() && m_d < m_n;
  220. pass = pass && m_dp > Integer::One() && m_dp.IsOdd() && m_dp < m_p;
  221. pass = pass && m_dq > Integer::One() && m_dq.IsOdd() && m_dq < m_q;
  222. pass = pass && m_u.IsPositive() && m_u < m_p;
  223. if (level >= 1)
  224. {
  225. pass = pass && m_p * m_q == m_n;
  226. pass = pass && m_e*m_d % LCM(m_p-1, m_q-1) == 1;
  227. pass = pass && m_dp == m_d%(m_p-1) && m_dq == m_d%(m_q-1);
  228. pass = pass && m_u * m_q % m_p == 1;
  229. }
  230. if (level >= 2)
  231. pass = pass && VerifyPrime(rng, m_p, level-2) && VerifyPrime(rng, m_q, level-2);
  232. return pass;
  233. }
  234. bool InvertibleRSAFunction::GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
  235. {
  236. return GetValueHelper<RSAFunction>(this, name, valueType, pValue).Assignable()
  237. CRYPTOPP_GET_FUNCTION_ENTRY(Prime1)
  238. CRYPTOPP_GET_FUNCTION_ENTRY(Prime2)
  239. CRYPTOPP_GET_FUNCTION_ENTRY(PrivateExponent)
  240. CRYPTOPP_GET_FUNCTION_ENTRY(ModPrime1PrivateExponent)
  241. CRYPTOPP_GET_FUNCTION_ENTRY(ModPrime2PrivateExponent)
  242. CRYPTOPP_GET_FUNCTION_ENTRY(MultiplicativeInverseOfPrime2ModPrime1)
  243. ;
  244. }
  245. void InvertibleRSAFunction::AssignFrom(const NameValuePairs &source)
  246. {
  247. AssignFromHelper<RSAFunction>(this, source)
  248. CRYPTOPP_SET_FUNCTION_ENTRY(Prime1)
  249. CRYPTOPP_SET_FUNCTION_ENTRY(Prime2)
  250. CRYPTOPP_SET_FUNCTION_ENTRY(PrivateExponent)
  251. CRYPTOPP_SET_FUNCTION_ENTRY(ModPrime1PrivateExponent)
  252. CRYPTOPP_SET_FUNCTION_ENTRY(ModPrime2PrivateExponent)
  253. CRYPTOPP_SET_FUNCTION_ENTRY(MultiplicativeInverseOfPrime2ModPrime1)
  254. ;
  255. }
  256. // *****************************************************************************
  257. Integer RSAFunction_ISO::ApplyFunction(const Integer &x) const
  258. {
  259. Integer t = RSAFunction::ApplyFunction(x);
  260. return t % 16 == 12 ? t : m_n - t;
  261. }
  262. Integer InvertibleRSAFunction_ISO::CalculateInverse(RandomNumberGenerator &rng, const Integer &x) const
  263. {
  264. Integer t = InvertibleRSAFunction::CalculateInverse(rng, x);
  265. return STDMIN(t, m_n-t);
  266. }
  267. NAMESPACE_END
  268. #endif