MPInteger.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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.Math.EC;
  6. namespace Best.HTTP.SecureProtocol.Org.BouncyCastle.Bcpg
  7. {
  8. /// <remarks>A multiple precision integer</remarks>
  9. public sealed class MPInteger
  10. : BcpgObject
  11. {
  12. private readonly BigInteger m_val;
  13. public MPInteger(BcpgInputStream bcpgIn)
  14. {
  15. if (bcpgIn == null)
  16. throw new ArgumentNullException(nameof(bcpgIn));
  17. int lengthInBits = (bcpgIn.ReadByte() << 8) | bcpgIn.ReadByte();
  18. int lengthInBytes = (lengthInBits + 7) / 8;
  19. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  20. Span<byte> bytes = lengthInBytes <= 512
  21. ? stackalloc byte[lengthInBytes]
  22. : new byte[lengthInBytes];
  23. #else
  24. byte[] bytes = new byte[lengthInBytes];
  25. #endif
  26. bcpgIn.ReadFully(bytes);
  27. m_val = new BigInteger(1, bytes);
  28. }
  29. public MPInteger(BigInteger val)
  30. {
  31. if (val == null)
  32. throw new ArgumentNullException(nameof(val));
  33. if (val.SignValue < 0)
  34. throw new ArgumentException("Values must be positive", nameof(val));
  35. m_val = val;
  36. }
  37. public BigInteger Value => m_val;
  38. public override void Encode(BcpgOutputStream bcpgOut)
  39. {
  40. bcpgOut.WriteShort((short)m_val.BitLength);
  41. bcpgOut.Write(m_val.ToByteArrayUnsigned());
  42. }
  43. internal static BigInteger ToMpiBigInteger(ECPoint point)
  44. {
  45. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  46. int encodedLength = point.GetEncodedLength(false);
  47. Span<byte> encoding = encodedLength <= 512
  48. ? stackalloc byte[encodedLength]
  49. : new byte[encodedLength];
  50. point.EncodeTo(false, encoding);
  51. #else
  52. byte[] encoding = point.GetEncoded(false);
  53. #endif
  54. return new BigInteger(1, encoding);
  55. }
  56. }
  57. }
  58. #pragma warning restore
  59. #endif