Counter Strike : Global Offensive Source Code
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.

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