DssKey.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using System.Security.Cryptography;
  2. using System.Text;
  3. namespace FxSsh.Algorithms
  4. {
  5. public class DssKey : PublicKeyAlgorithm
  6. {
  7. private readonly DSACryptoServiceProvider _algorithm = new DSACryptoServiceProvider();
  8. public DssKey(string key = null)
  9. : base(key)
  10. {
  11. }
  12. public override string Name
  13. {
  14. get { return "ssh-dss"; }
  15. }
  16. public override void ImportKey(byte[] bytes)
  17. {
  18. _algorithm.ImportCspBlob(bytes);
  19. }
  20. public override byte[] ExportKey()
  21. {
  22. return _algorithm.ExportCspBlob(true);
  23. }
  24. public override void LoadKeyAndCertificatesData(byte[] data)
  25. {
  26. using (var worker = new SshDataWorker(data))
  27. {
  28. if (worker.ReadString(Encoding.ASCII) != this.Name)
  29. throw new CryptographicException("Key and certificates were not created with this algorithm.");
  30. var args = new DSAParameters();
  31. args.P = worker.ReadMpint();
  32. args.Q = worker.ReadMpint();
  33. args.G = worker.ReadMpint();
  34. args.Y = worker.ReadMpint();
  35. _algorithm.ImportParameters(args);
  36. }
  37. }
  38. public override byte[] CreateKeyAndCertificatesData()
  39. {
  40. using (var worker = new SshDataWorker())
  41. {
  42. var args = _algorithm.ExportParameters(false);
  43. worker.Write(this.Name, Encoding.ASCII);
  44. worker.WriteMpint(args.P);
  45. worker.WriteMpint(args.Q);
  46. worker.WriteMpint(args.G);
  47. worker.WriteMpint(args.Y);
  48. return worker.ToByteArray();
  49. }
  50. }
  51. public override bool VerifyData(byte[] data, byte[] signature)
  52. {
  53. return _algorithm.VerifyData(data, signature);
  54. }
  55. public override bool VerifyHash(byte[] hash, byte[] signature)
  56. {
  57. return _algorithm.VerifyHash(hash, "SHA1", signature);
  58. }
  59. public override byte[] SignData(byte[] data)
  60. {
  61. return _algorithm.SignData(data);
  62. }
  63. public override byte[] SignHash(byte[] hash)
  64. {
  65. return _algorithm.SignHash(hash, "SHA1");
  66. }
  67. }
  68. }