RSAPublicKeyStructure.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Math;
  5. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Utilities;
  6. namespace Best.HTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509
  7. {
  8. public class RsaPublicKeyStructure
  9. : Asn1Encodable
  10. {
  11. private BigInteger modulus;
  12. private BigInteger publicExponent;
  13. public static RsaPublicKeyStructure GetInstance(
  14. Asn1TaggedObject obj,
  15. bool explicitly)
  16. {
  17. return GetInstance(Asn1Sequence.GetInstance(obj, explicitly));
  18. }
  19. public static RsaPublicKeyStructure GetInstance(
  20. object obj)
  21. {
  22. if (obj == null || obj is RsaPublicKeyStructure)
  23. {
  24. return (RsaPublicKeyStructure) obj;
  25. }
  26. if (obj is Asn1Sequence)
  27. {
  28. return new RsaPublicKeyStructure((Asn1Sequence) obj);
  29. }
  30. throw new ArgumentException("Invalid RsaPublicKeyStructure: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj));
  31. }
  32. public RsaPublicKeyStructure(
  33. BigInteger modulus,
  34. BigInteger publicExponent)
  35. {
  36. if (modulus == null)
  37. throw new ArgumentNullException("modulus");
  38. if (publicExponent == null)
  39. throw new ArgumentNullException("publicExponent");
  40. if (modulus.SignValue <= 0)
  41. throw new ArgumentException("Not a valid RSA modulus", "modulus");
  42. if (publicExponent.SignValue <= 0)
  43. throw new ArgumentException("Not a valid RSA public exponent", "publicExponent");
  44. this.modulus = modulus;
  45. this.publicExponent = publicExponent;
  46. }
  47. private RsaPublicKeyStructure(
  48. Asn1Sequence seq)
  49. {
  50. if (seq.Count != 2)
  51. throw new ArgumentException("Bad sequence size: " + seq.Count);
  52. // Note: we are accepting technically incorrect (i.e. negative) values here
  53. modulus = DerInteger.GetInstance(seq[0]).PositiveValue;
  54. publicExponent = DerInteger.GetInstance(seq[1]).PositiveValue;
  55. }
  56. public BigInteger Modulus
  57. {
  58. get { return modulus; }
  59. }
  60. public BigInteger PublicExponent
  61. {
  62. get { return publicExponent; }
  63. }
  64. /**
  65. * This outputs the key in Pkcs1v2 format.
  66. * <pre>
  67. * RSAPublicKey ::= Sequence {
  68. * modulus Integer, -- n
  69. * publicExponent Integer, -- e
  70. * }
  71. * </pre>
  72. */
  73. public override Asn1Object ToAsn1Object()
  74. {
  75. return new DerSequence(
  76. new DerInteger(Modulus),
  77. new DerInteger(PublicExponent));
  78. }
  79. }
  80. }
  81. #pragma warning restore
  82. #endif