RsaKeyParameters.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
  5. using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
  6. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
  7. {
  8. public class RsaKeyParameters
  9. : AsymmetricKeyParameter
  10. {
  11. // the value is the product of the 132 smallest primes from 3 to 751
  12. private static BigInteger SmallPrimesProduct = new BigInteger(
  13. "8138E8A0FCF3A4E84A771D40FD305D7F4AA59306D7251DE54D98AF8FE95729A1" +
  14. "F73D893FA424CD2EDC8636A6C3285E022B0E3866A565AE8108EED8591CD4FE8D" +
  15. "2CE86165A978D719EBF647F362D33FCA29CD179FB42401CBAF3DF0C614056F9C" +
  16. "8F3CFD51E474AFB6BC6974F78DB8ABA8E9E517FDED658591AB7502BD41849462F",
  17. 16);
  18. private static BigInteger Validate(BigInteger modulus)
  19. {
  20. if ((modulus.IntValue & 1) == 0)
  21. throw new ArgumentException("RSA modulus is even", "modulus");
  22. if (!modulus.Gcd(SmallPrimesProduct).Equals(BigInteger.One))
  23. throw new ArgumentException("RSA modulus has a small prime factor");
  24. // TODO: add additional primePower/Composite test - expensive!!
  25. return modulus;
  26. }
  27. private readonly BigInteger modulus;
  28. private readonly BigInteger exponent;
  29. public RsaKeyParameters(
  30. bool isPrivate,
  31. BigInteger modulus,
  32. BigInteger exponent)
  33. : base(isPrivate)
  34. {
  35. if (modulus == null)
  36. throw new ArgumentNullException("modulus");
  37. if (exponent == null)
  38. throw new ArgumentNullException("exponent");
  39. if (modulus.SignValue <= 0)
  40. throw new ArgumentException("Not a valid RSA modulus", "modulus");
  41. if (exponent.SignValue <= 0)
  42. throw new ArgumentException("Not a valid RSA exponent", "exponent");
  43. if (!isPrivate && (exponent.IntValue & 1) == 0)
  44. throw new ArgumentException("RSA publicExponent is even", "exponent");
  45. this.modulus = Validate(modulus);
  46. this.exponent = exponent;
  47. }
  48. public BigInteger Modulus
  49. {
  50. get { return modulus; }
  51. }
  52. public BigInteger Exponent
  53. {
  54. get { return exponent; }
  55. }
  56. public override bool Equals(
  57. object obj)
  58. {
  59. RsaKeyParameters kp = obj as RsaKeyParameters;
  60. if (kp == null)
  61. {
  62. return false;
  63. }
  64. return kp.IsPrivate == this.IsPrivate
  65. && kp.Modulus.Equals(this.modulus)
  66. && kp.Exponent.Equals(this.exponent);
  67. }
  68. public override int GetHashCode()
  69. {
  70. return modulus.GetHashCode() ^ exponent.GetHashCode() ^ IsPrivate.GetHashCode();
  71. }
  72. }
  73. }
  74. #pragma warning restore
  75. #endif