X25519PrivateKeyParameters.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using System.IO;
  5. using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Rfc7748;
  6. using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
  7. using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
  8. using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO;
  9. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
  10. {
  11. public sealed class X25519PrivateKeyParameters
  12. : AsymmetricKeyParameter
  13. {
  14. public static readonly int KeySize = X25519.ScalarSize;
  15. public static readonly int SecretSize = X25519.PointSize;
  16. private readonly byte[] data = new byte[KeySize];
  17. public X25519PrivateKeyParameters(SecureRandom random)
  18. : base(true)
  19. {
  20. X25519.GeneratePrivateKey(random, data);
  21. }
  22. public X25519PrivateKeyParameters(byte[] buf, int off)
  23. : base(true)
  24. {
  25. Array.Copy(buf, off, data, 0, KeySize);
  26. }
  27. public X25519PrivateKeyParameters(Stream input)
  28. : base(true)
  29. {
  30. if (KeySize != Streams.ReadFully(input, data))
  31. throw new EndOfStreamException("EOF encountered in middle of X25519 private key");
  32. }
  33. public void Encode(byte[] buf, int off)
  34. {
  35. Array.Copy(data, 0, buf, off, KeySize);
  36. }
  37. public byte[] GetEncoded()
  38. {
  39. return Arrays.Clone(data);
  40. }
  41. public X25519PublicKeyParameters GeneratePublicKey()
  42. {
  43. byte[] publicKey = new byte[X25519.PointSize];
  44. X25519.GeneratePublicKey(data, 0, publicKey, 0);
  45. return new X25519PublicKeyParameters(publicKey, 0);
  46. }
  47. public void GenerateSecret(X25519PublicKeyParameters publicKey, byte[] buf, int off)
  48. {
  49. byte[] encoded = new byte[X25519.PointSize];
  50. publicKey.Encode(encoded, 0);
  51. if (!X25519.CalculateAgreement(data, 0, encoded, 0, buf, off))
  52. throw new InvalidOperationException("X25519 agreement failed");
  53. }
  54. }
  55. }
  56. #pragma warning restore
  57. #endif