Ed25519phSigner.cs 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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.Crypto.Parameters;
  6. using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Rfc8032;
  7. using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
  8. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Signers
  9. {
  10. public class Ed25519phSigner
  11. : ISigner
  12. {
  13. private readonly IDigest prehash = Ed25519.CreatePrehash();
  14. private readonly byte[] context;
  15. private bool forSigning;
  16. private Ed25519PrivateKeyParameters privateKey;
  17. private Ed25519PublicKeyParameters publicKey;
  18. public Ed25519phSigner(byte[] context)
  19. {
  20. this.context = Arrays.Clone(context);
  21. }
  22. public virtual string AlgorithmName
  23. {
  24. get { return "Ed25519ph"; }
  25. }
  26. public virtual void Init(bool forSigning, ICipherParameters parameters)
  27. {
  28. this.forSigning = forSigning;
  29. if (forSigning)
  30. {
  31. this.privateKey = (Ed25519PrivateKeyParameters)parameters;
  32. this.publicKey = null;
  33. }
  34. else
  35. {
  36. this.privateKey = null;
  37. this.publicKey = (Ed25519PublicKeyParameters)parameters;
  38. }
  39. Reset();
  40. }
  41. public virtual void Update(byte b)
  42. {
  43. prehash.Update(b);
  44. }
  45. public virtual void BlockUpdate(byte[] buf, int off, int len)
  46. {
  47. prehash.BlockUpdate(buf, off, len);
  48. }
  49. public virtual byte[] GenerateSignature()
  50. {
  51. if (!forSigning || null == privateKey)
  52. throw new InvalidOperationException("Ed25519phSigner not initialised for signature generation.");
  53. byte[] msg = new byte[Ed25519.PrehashSize];
  54. if (Ed25519.PrehashSize != prehash.DoFinal(msg, 0))
  55. throw new InvalidOperationException("Prehash digest failed");
  56. byte[] signature = new byte[Ed25519PrivateKeyParameters.SignatureSize];
  57. privateKey.Sign(Ed25519.Algorithm.Ed25519ph, context, msg, 0, Ed25519.PrehashSize, signature, 0);
  58. return signature;
  59. }
  60. public virtual bool VerifySignature(byte[] signature)
  61. {
  62. if (forSigning || null == publicKey)
  63. throw new InvalidOperationException("Ed25519phSigner not initialised for verification");
  64. if (Ed25519.SignatureSize != signature.Length)
  65. {
  66. prehash.Reset();
  67. return false;
  68. }
  69. byte[] pk = publicKey.GetEncoded();
  70. return Ed25519.VerifyPrehash(signature, 0, pk, 0, context, prehash);
  71. }
  72. public void Reset()
  73. {
  74. prehash.Reset();
  75. }
  76. }
  77. }
  78. #pragma warning restore
  79. #endif