ED25519DigitalSignature.cs 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. using System;
  2. using Renci.SshNet.Common;
  3. using Renci.SshNet.Security.Chaos.NaCl;
  4. namespace Renci.SshNet.Security.Cryptography
  5. {
  6. /// <summary>
  7. /// Implements ECDSA digital signature algorithm.
  8. /// </summary>
  9. public class ED25519DigitalSignature : DigitalSignature, IDisposable
  10. {
  11. private readonly ED25519Key _key;
  12. private bool _isDisposed;
  13. /// <summary>
  14. /// Initializes a new instance of the <see cref="ED25519DigitalSignature" /> class.
  15. /// </summary>
  16. /// <param name="key">The ED25519Key key.</param>
  17. /// <exception cref="ArgumentNullException"><paramref name="key"/> is <see langword="null"/>.</exception>
  18. public ED25519DigitalSignature(ED25519Key key)
  19. {
  20. if (key is null)
  21. {
  22. throw new ArgumentNullException(nameof(key));
  23. }
  24. _key = key;
  25. }
  26. /// <summary>
  27. /// Verifies the signature.
  28. /// </summary>
  29. /// <param name="input">The input.</param>
  30. /// <param name="signature">The signature.</param>
  31. /// <returns>
  32. /// <see langword="true"/> if signature was successfully verified; otherwise <see langword="false"/>.
  33. /// </returns>
  34. /// <exception cref="InvalidOperationException">Invalid signature.</exception>
  35. public override bool Verify(byte[] input, byte[] signature)
  36. {
  37. return Ed25519.Verify(signature, input, _key.PublicKey);
  38. }
  39. /// <summary>
  40. /// Creates the signature.
  41. /// </summary>
  42. /// <param name="input">The input.</param>
  43. /// <returns>
  44. /// Signed input data.
  45. /// </returns>
  46. /// <exception cref="SshException">Invalid ED25519Key key.</exception>
  47. public override byte[] Sign(byte[] input)
  48. {
  49. return Ed25519.Sign(input, _key.PrivateKey);
  50. }
  51. /// <summary>
  52. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  53. /// </summary>
  54. public void Dispose()
  55. {
  56. Dispose(disposing: true);
  57. GC.SuppressFinalize(this);
  58. }
  59. /// <summary>
  60. /// Releases unmanaged and - optionally - managed resources.
  61. /// </summary>
  62. /// <param name="disposing"><see langword="true"/> to release both managed and unmanaged resources; <see langword="false"/> to release only unmanaged resources.</param>
  63. protected virtual void Dispose(bool disposing)
  64. {
  65. if (_isDisposed)
  66. {
  67. return;
  68. }
  69. if (disposing)
  70. {
  71. _isDisposed = true;
  72. }
  73. }
  74. /// <summary>
  75. /// Finalizes an instance of the <see cref="ED25519DigitalSignature"/> class.
  76. /// </summary>
  77. ~ED25519DigitalSignature()
  78. {
  79. Dispose(disposing: false);
  80. }
  81. }
  82. }