RsaKey.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using System.Security.Cryptography;
  2. using System.Text;
  3. namespace FxSsh.Algorithms
  4. {
  5. public class RsaKey : PublicKeyAlgorithm
  6. {
  7. private readonly RSACryptoServiceProvider _algorithm = new RSACryptoServiceProvider();
  8. public RsaKey(string key = null)
  9. : base(key)
  10. {
  11. }
  12. public override string Name
  13. {
  14. get { return "ssh-rsa"; }
  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 RSAParameters();
  31. args.Exponent = worker.ReadMpint();
  32. args.Modulus = worker.ReadMpint();
  33. _algorithm.ImportParameters(args);
  34. }
  35. }
  36. public override byte[] CreateKeyAndCertificatesData()
  37. {
  38. using (var worker = new SshDataWorker())
  39. {
  40. var args = _algorithm.ExportParameters(false);
  41. worker.Write(this.Name, Encoding.ASCII);
  42. worker.WriteMpint(args.Exponent);
  43. worker.WriteMpint(args.Modulus);
  44. return worker.ToByteArray();
  45. }
  46. }
  47. public override bool VerifyData(byte[] data, byte[] signature)
  48. {
  49. return _algorithm.VerifyData(data, signature, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
  50. }
  51. public override bool VerifyHash(byte[] hash, byte[] signature)
  52. {
  53. return _algorithm.VerifyHash(hash, signature, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
  54. }
  55. public override byte[] SignData(byte[] data)
  56. {
  57. return _algorithm.SignData(data, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
  58. }
  59. public override byte[] SignHash(byte[] hash)
  60. {
  61. return _algorithm.SignHash(hash, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
  62. }
  63. }
  64. }