RsaKeyParameters.cs 2.8 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. // Hexadecimal value of the product of the 131 smallest odd primes from 3 to 743
  12. private static readonly BigInteger SmallPrimesProduct = new BigInteger(
  13. "8138e8a0fcf3a4e84a771d40fd305d7f4aa59306d7251de54d98af8fe95729a1f"
  14. + "73d893fa424cd2edc8636a6c3285e022b0e3866a565ae8108eed8591cd4fe8d2"
  15. + "ce86165a978d719ebf647f362d33fca29cd179fb42401cbaf3df0c614056f9c8"
  16. + "f3cfd51e474afb6bc6974f78db8aba8e9e517fded658591ab7502bd41849462f",
  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