PlainDsaEncoding.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
  5. using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
  6. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Signers
  7. {
  8. public class PlainDsaEncoding
  9. : IDsaEncoding
  10. {
  11. public static readonly PlainDsaEncoding Instance = new PlainDsaEncoding();
  12. public virtual BigInteger[] Decode(BigInteger n, byte[] encoding)
  13. {
  14. int valueLength = BigIntegers.GetUnsignedByteLength(n);
  15. if (encoding.Length != valueLength * 2)
  16. throw new ArgumentException("Encoding has incorrect length", "encoding");
  17. return new BigInteger[] {
  18. DecodeValue(n, encoding, 0, valueLength),
  19. DecodeValue(n, encoding, valueLength, valueLength),
  20. };
  21. }
  22. public virtual byte[] Encode(BigInteger n, BigInteger r, BigInteger s)
  23. {
  24. int valueLength = BigIntegers.GetUnsignedByteLength(n);
  25. byte[] result = new byte[valueLength * 2];
  26. EncodeValue(n, r, result, 0, valueLength);
  27. EncodeValue(n, s, result, valueLength, valueLength);
  28. return result;
  29. }
  30. protected virtual BigInteger CheckValue(BigInteger n, BigInteger x)
  31. {
  32. if (x.SignValue < 0 || x.CompareTo(n) >= 0)
  33. throw new ArgumentException("Value out of range", "x");
  34. return x;
  35. }
  36. protected virtual BigInteger DecodeValue(BigInteger n, byte[] buf, int off, int len)
  37. {
  38. return CheckValue(n, new BigInteger(1, buf, off, len));
  39. }
  40. protected virtual void EncodeValue(BigInteger n, BigInteger x, byte[] buf, int off, int len)
  41. {
  42. byte[] bs = CheckValue(n, x).ToByteArrayUnsigned();
  43. int bsOff = System.Math.Max(0, bs.Length - len);
  44. int bsLen = bs.Length - bsOff;
  45. int pos = len - bsLen;
  46. Arrays.Fill(buf, off, off + pos, 0);
  47. Array.Copy(bs, bsOff, buf, off + pos, bsLen);
  48. }
  49. }
  50. }
  51. #pragma warning restore
  52. #endif