RsaKey.cs 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. #nullable enable
  2. using System;
  3. using System.Formats.Asn1;
  4. using System.Numerics;
  5. using System.Security.Cryptography;
  6. using Renci.SshNet.Common;
  7. using Renci.SshNet.Security.Cryptography;
  8. namespace Renci.SshNet.Security
  9. {
  10. /// <summary>
  11. /// Contains the RSA private and public key.
  12. /// </summary>
  13. public class RsaKey : Key, IDisposable
  14. {
  15. private RsaDigitalSignature? _digitalSignature;
  16. /// <summary>
  17. /// Gets the name of the key.
  18. /// </summary>
  19. /// <returns>
  20. /// The name of the key.
  21. /// </returns>
  22. public override string ToString()
  23. {
  24. return "ssh-rsa";
  25. }
  26. internal RSA RSA { get; }
  27. /// <summary>
  28. /// Gets the modulus.
  29. /// </summary>
  30. /// <value>
  31. /// The modulus.
  32. /// </value>
  33. public BigInteger Modulus { get; }
  34. /// <summary>
  35. /// Gets the exponent.
  36. /// </summary>
  37. /// <value>
  38. /// The exponent.
  39. /// </value>
  40. public BigInteger Exponent { get; }
  41. /// <summary>
  42. /// Gets the D.
  43. /// </summary>
  44. /// <value>
  45. /// The D.
  46. /// </value>
  47. public BigInteger D { get; }
  48. /// <summary>
  49. /// Gets the P.
  50. /// </summary>
  51. /// <value>
  52. /// The P.
  53. /// </value>
  54. public BigInteger P { get; }
  55. /// <summary>
  56. /// Gets the Q.
  57. /// </summary>
  58. /// <value>
  59. /// The Q.
  60. /// </value>
  61. public BigInteger Q { get; }
  62. /// <summary>
  63. /// Gets the DP.
  64. /// </summary>
  65. /// <value>
  66. /// The DP.
  67. /// </value>
  68. public BigInteger DP { get; }
  69. /// <summary>
  70. /// Gets the DQ.
  71. /// </summary>
  72. /// <value>
  73. /// The DQ.
  74. /// </value>
  75. public BigInteger DQ { get; }
  76. /// <summary>
  77. /// Gets the inverse Q.
  78. /// </summary>
  79. /// <value>
  80. /// The inverse Q.
  81. /// </value>
  82. public BigInteger InverseQ { get; }
  83. /// <inheritdoc/>
  84. public override int KeyLength
  85. {
  86. get
  87. {
  88. return (int)Modulus.GetBitLength();
  89. }
  90. }
  91. /// <summary>
  92. /// Gets the digital signature implementation for this key.
  93. /// </summary>
  94. /// <value>
  95. /// An implementation of an RSA digital signature using the SHA-1 hash algorithm.
  96. /// </value>
  97. protected internal override DigitalSignature DigitalSignature
  98. {
  99. get
  100. {
  101. _digitalSignature ??= new RsaDigitalSignature(this);
  102. return _digitalSignature;
  103. }
  104. }
  105. /// <summary>
  106. /// Gets the RSA public key.
  107. /// </summary>
  108. /// <value>
  109. /// An array with <see cref="Exponent"/> at index 0, and <see cref="Modulus"/>
  110. /// at index 1.
  111. /// </value>
  112. public override BigInteger[] Public
  113. {
  114. get
  115. {
  116. return new[] { Exponent, Modulus };
  117. }
  118. }
  119. /// <summary>
  120. /// Initializes a new instance of the <see cref="RsaKey"/> class.
  121. /// </summary>
  122. /// <param name="publicKeyData">The encoded public key data.</param>
  123. public RsaKey(SshKeyData publicKeyData)
  124. {
  125. ThrowHelper.ThrowIfNull(publicKeyData);
  126. if (publicKeyData.Name != "ssh-rsa" || publicKeyData.Keys.Length != 2)
  127. {
  128. throw new ArgumentException($"Invalid RSA public key data. ({publicKeyData.Name}, {publicKeyData.Keys.Length}).", nameof(publicKeyData));
  129. }
  130. Exponent = publicKeyData.Keys[0];
  131. Modulus = publicKeyData.Keys[1];
  132. RSA = RSA.Create();
  133. RSA.ImportParameters(GetRSAParameters());
  134. }
  135. /// <summary>
  136. /// Initializes a new instance of the <see cref="RsaKey"/> class.
  137. /// </summary>
  138. /// <param name="privateKeyData">DER encoded private key data.</param>
  139. public RsaKey(byte[] privateKeyData)
  140. {
  141. ThrowHelper.ThrowIfNull(privateKeyData);
  142. var keyReader = new AsnReader(privateKeyData, AsnEncodingRules.DER);
  143. var sequenceReader = keyReader.ReadSequence();
  144. keyReader.ThrowIfNotEmpty();
  145. _ = sequenceReader.ReadInteger(); // skip version
  146. Modulus = sequenceReader.ReadInteger();
  147. Exponent = sequenceReader.ReadInteger();
  148. D = sequenceReader.ReadInteger();
  149. P = sequenceReader.ReadInteger();
  150. Q = sequenceReader.ReadInteger();
  151. DP = sequenceReader.ReadInteger();
  152. DQ = sequenceReader.ReadInteger();
  153. InverseQ = sequenceReader.ReadInteger();
  154. sequenceReader.ThrowIfNotEmpty();
  155. RSA = RSA.Create();
  156. RSA.ImportParameters(GetRSAParameters());
  157. }
  158. /// <summary>
  159. /// Initializes a new instance of the <see cref="RsaKey"/> class.
  160. /// </summary>
  161. /// <param name="modulus">The modulus.</param>
  162. /// <param name="exponent">The exponent.</param>
  163. /// <param name="d">The d.</param>
  164. /// <param name="p">The p.</param>
  165. /// <param name="q">The q.</param>
  166. /// <param name="inverseQ">The inverse Q.</param>
  167. public RsaKey(BigInteger modulus, BigInteger exponent, BigInteger d, BigInteger p, BigInteger q, BigInteger inverseQ)
  168. {
  169. Modulus = modulus;
  170. Exponent = exponent;
  171. D = d;
  172. P = p;
  173. Q = q;
  174. DP = PrimeExponent(d, p);
  175. DQ = PrimeExponent(d, q);
  176. InverseQ = inverseQ;
  177. RSA = RSA.Create();
  178. RSA.ImportParameters(GetRSAParameters());
  179. }
  180. internal RSAParameters GetRSAParameters()
  181. {
  182. // Specification of the RSAParameters fields (taken from the CryptographicException
  183. // thrown when not done correctly):
  184. // Exponent and Modulus are required. If D is present, it must have the same length
  185. // as Modulus. If D is present, P, Q, DP, DQ, and InverseQ are required and must
  186. // have half the length of Modulus, rounded up, otherwise they must be omitted.
  187. // See also https://github.com/dotnet/runtime/blob/9b57a265c7efd3732b035bade005561a04767128/src/libraries/Common/src/System/Security/Cryptography/RSAKeyFormatHelper.cs#L42
  188. if (D.IsZero)
  189. {
  190. // Public key
  191. return new RSAParameters()
  192. {
  193. Modulus = Modulus.ToByteArray(isUnsigned: true, isBigEndian: true),
  194. Exponent = Exponent.ToByteArray(isUnsigned: true, isBigEndian: true),
  195. };
  196. }
  197. var n = Modulus.ToByteArray(isUnsigned: true, isBigEndian: true);
  198. var halfModulusLength = (n.Length + 1) / 2;
  199. return new RSAParameters()
  200. {
  201. Modulus = n,
  202. Exponent = Exponent.ToByteArray(isUnsigned: true, isBigEndian: true),
  203. D = D.ExportKeyParameter(n.Length),
  204. P = P.ExportKeyParameter(halfModulusLength),
  205. Q = Q.ExportKeyParameter(halfModulusLength),
  206. DP = DP.ExportKeyParameter(halfModulusLength),
  207. DQ = DQ.ExportKeyParameter(halfModulusLength),
  208. InverseQ = InverseQ.ExportKeyParameter(halfModulusLength),
  209. };
  210. }
  211. private static BigInteger PrimeExponent(BigInteger privateExponent, BigInteger prime)
  212. {
  213. var pe = prime - BigInteger.One;
  214. return privateExponent % pe;
  215. }
  216. /// <summary>
  217. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  218. /// </summary>
  219. public void Dispose()
  220. {
  221. Dispose(disposing: true);
  222. GC.SuppressFinalize(this);
  223. }
  224. /// <summary>
  225. /// Releases unmanaged and - optionally - managed resources.
  226. /// </summary>
  227. /// <param name="disposing"><see langword="true"/> to release both managed and unmanaged resources; <see langword="false"/> to release only unmanaged resources.</param>
  228. protected virtual void Dispose(bool disposing)
  229. {
  230. if (disposing)
  231. {
  232. _digitalSignature?.Dispose();
  233. RSA.Dispose();
  234. }
  235. }
  236. }
  237. }