Key.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using System;
  2. using System.Collections.Generic;
  3. using Renci.SshNet.Common;
  4. using Renci.SshNet.Security.Cryptography;
  5. namespace Renci.SshNet.Security
  6. {
  7. /// <summary>
  8. /// Base class for asymmetric cipher algorithms
  9. /// </summary>
  10. public abstract class Key
  11. {
  12. /// <summary>
  13. /// Specifies array of big integers that represent private key
  14. /// </summary>
  15. protected BigInteger[] _privateKey;
  16. /// <summary>
  17. /// Gets the key specific digital signature.
  18. /// </summary>
  19. protected abstract DigitalSignature DigitalSignature { get; }
  20. /// <summary>
  21. /// Gets or sets the public key.
  22. /// </summary>
  23. /// <value>
  24. /// The public.
  25. /// </value>
  26. public abstract BigInteger[] Public { get; set; }
  27. /// <summary>
  28. /// Gets the length of the key.
  29. /// </summary>
  30. /// <value>
  31. /// The length of the key.
  32. /// </value>
  33. public abstract int KeyLength { get; }
  34. /// <summary>
  35. /// Initializes a new instance of the <see cref="Key"/> class.
  36. /// </summary>
  37. /// <param name="data">DER encoded private key data.</param>
  38. public Key(byte[] data)
  39. {
  40. if (data == null)
  41. throw new ArgumentNullException("data");
  42. var der = new DerData(data);
  43. var version = der.ReadBigInteger();
  44. var keys = new List<BigInteger>();
  45. while (!der.IsEndOfData)
  46. {
  47. keys.Add(der.ReadBigInteger());
  48. }
  49. this._privateKey = keys.ToArray();
  50. }
  51. /// <summary>
  52. /// Initializes a new instance of the <see cref="Key"/> class.
  53. /// </summary>
  54. public Key()
  55. {
  56. }
  57. /// <summary>
  58. /// Signs the specified data with the key.
  59. /// </summary>
  60. /// <param name="data">The data to sign.</param>
  61. /// <returns>
  62. /// Signed data.
  63. /// </returns>
  64. public byte[] Sign(byte[] data)
  65. {
  66. return this.DigitalSignature.Sign(data);
  67. }
  68. /// <summary>
  69. /// Verifies the signature.
  70. /// </summary>
  71. /// <param name="data">The data to verify.</param>
  72. /// <param name="signature">The signature to verify against.</param>
  73. /// <returns><c>True</c> is signature was successfully verifies; otherwise <c>false</c>.</returns>
  74. public bool VerifySignature(byte[] data, byte[] signature)
  75. {
  76. return this.DigitalSignature.Verify(data, signature);
  77. }
  78. }
  79. }