X25519PrivateKeyParameters.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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)
  23. : this(Validate(buf), 0)
  24. {
  25. }
  26. public X25519PrivateKeyParameters(byte[] buf, int off)
  27. : base(true)
  28. {
  29. Array.Copy(buf, off, data, 0, KeySize);
  30. }
  31. public X25519PrivateKeyParameters(Stream input)
  32. : base(true)
  33. {
  34. if (KeySize != Streams.ReadFully(input, data))
  35. throw new EndOfStreamException("EOF encountered in middle of X25519 private key");
  36. }
  37. public void Encode(byte[] buf, int off)
  38. {
  39. Array.Copy(data, 0, buf, off, KeySize);
  40. }
  41. public byte[] GetEncoded()
  42. {
  43. return Arrays.Clone(data);
  44. }
  45. public X25519PublicKeyParameters GeneratePublicKey()
  46. {
  47. byte[] publicKey = new byte[X25519.PointSize];
  48. X25519.GeneratePublicKey(data, 0, publicKey, 0);
  49. return new X25519PublicKeyParameters(publicKey, 0);
  50. }
  51. public void GenerateSecret(X25519PublicKeyParameters publicKey, byte[] buf, int off)
  52. {
  53. byte[] encoded = new byte[X25519.PointSize];
  54. publicKey.Encode(encoded, 0);
  55. if (!X25519.CalculateAgreement(data, 0, encoded, 0, buf, off))
  56. throw new InvalidOperationException("X25519 agreement failed");
  57. }
  58. private static byte[] Validate(byte[] buf)
  59. {
  60. if (buf.Length != KeySize)
  61. throw new ArgumentException("must have length " + KeySize, "buf");
  62. return buf;
  63. }
  64. }
  65. }
  66. #pragma warning restore
  67. #endif