DsaDigitalSignatureTest.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. using System.Text;
  2. using Microsoft.VisualStudio.TestTools.UnitTesting;
  3. using Renci.SshNet.Abstractions;
  4. #if !NET6_0_OR_GREATER
  5. using Renci.SshNet.Common;
  6. #endif
  7. using Renci.SshNet.Security;
  8. using Renci.SshNet.Security.Cryptography;
  9. using Renci.SshNet.Tests.Common;
  10. namespace Renci.SshNet.Tests.Classes.Security.Cryptography
  11. {
  12. [TestClass]
  13. public class DsaDigitalSignatureTest : TestBase
  14. {
  15. [TestMethod]
  16. public void Verify()
  17. {
  18. byte[] data = Encoding.UTF8.GetBytes("Hello, World!");
  19. DsaKey dsaKey = GetDsaKey("Key.DSA.txt");
  20. Assert.AreEqual(1024, dsaKey.P.GetBitLength());
  21. Assert.AreEqual(160, dsaKey.Q.GetBitLength());
  22. var digitalSignature = new DsaDigitalSignature(dsaKey);
  23. byte[] signedBytes = digitalSignature.Sign(data);
  24. // We can't compare signatures for value equality because they have a source of randomness
  25. Assert.AreEqual(40, signedBytes.Length);
  26. Assert.IsTrue(digitalSignature.Verify(data, signedBytes));
  27. byte[] signatureToVerify = new byte[]
  28. {
  29. // Generated with a previous DsaDigitalSignature implementation in order to confirm consistent
  30. // behaviour. We can't seem to validate against openssl because openssl outputs a DER signature,
  31. // where as we want IEEE P1363 (fixed size) format.
  32. 0x07, 0x4c, 0x5e, 0x15, 0x53, 0x36, 0x21, 0xbe, 0x5a, 0x82, 0x35, 0xd5, 0xb6, 0xe6, 0x7d, 0x2f,
  33. 0x01, 0x2a, 0x78, 0x9b, 0x16, 0x4a, 0xe5, 0x8d, 0x85, 0xa6, 0x34, 0x56, 0x9d, 0x38, 0xd6, 0x1a,
  34. 0xa4, 0xa1, 0x5b, 0x98, 0x7d, 0xd5, 0x35, 0x40
  35. };
  36. Assert.IsTrue(digitalSignature.Verify(data, signatureToVerify));
  37. Assert.IsFalse(digitalSignature.Verify(data, CryptoAbstraction.GenerateRandom(40)));
  38. }
  39. private static DsaKey GetDsaKey(string fileName, string passPhrase = null)
  40. {
  41. using (var stream = GetData(fileName))
  42. {
  43. return (DsaKey)new PrivateKeyFile(stream, passPhrase).Key;
  44. }
  45. }
  46. }
  47. }