RSAPublicKeyStructure.cs 2.8 KB

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