RSAPublicKeyStructure.cs 2.7 KB

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