StandardDsaEncoding.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
  5. using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
  6. using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
  7. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Signers
  8. {
  9. public class StandardDsaEncoding
  10. : IDsaEncoding
  11. {
  12. public static readonly StandardDsaEncoding Instance = new StandardDsaEncoding();
  13. public virtual BigInteger[] Decode(BigInteger n, byte[] encoding)
  14. {
  15. Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(encoding);
  16. if (seq.Count == 2)
  17. {
  18. BigInteger r = DecodeValue(n, seq, 0);
  19. BigInteger s = DecodeValue(n, seq, 1);
  20. byte[] expectedEncoding = Encode(n, r, s);
  21. if (Arrays.AreEqual(expectedEncoding, encoding))
  22. return new BigInteger[]{ r, s };
  23. }
  24. throw new ArgumentException("Malformed signature", "encoding");
  25. }
  26. public virtual byte[] Encode(BigInteger n, BigInteger r, BigInteger s)
  27. {
  28. return new DerSequence(
  29. EncodeValue(n, r),
  30. EncodeValue(n, s)
  31. ).GetEncoded(Asn1Encodable.Der);
  32. }
  33. protected virtual BigInteger CheckValue(BigInteger n, BigInteger x)
  34. {
  35. if (x.SignValue < 0 || (null != n && x.CompareTo(n) >= 0))
  36. throw new ArgumentException("Value out of range", "x");
  37. return x;
  38. }
  39. protected virtual BigInteger DecodeValue(BigInteger n, Asn1Sequence s, int pos)
  40. {
  41. return CheckValue(n, ((DerInteger)s[pos]).Value);
  42. }
  43. protected virtual DerInteger EncodeValue(BigInteger n, BigInteger x)
  44. {
  45. return new DerInteger(CheckValue(n, x));
  46. }
  47. }
  48. }
  49. #pragma warning restore
  50. #endif