<PackageReference Include="SSH.NET" Version="2024.2.0" />

PrivateKeyFile

Represents private key information.
using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.EdEC; using Org.BouncyCastle.Asn1.Pkcs; using Org.BouncyCastle.Asn1.X9; using Org.BouncyCastle.Pkcs; using Renci.SshNet.Common; using Renci.SshNet.Security; using Renci.SshNet.Security.Cryptography; using Renci.SshNet.Security.Cryptography.Ciphers; using Renci.SshNet.Security.Cryptography.Ciphers.Modes; using Renci.SshNet.Security.Cryptography.Ciphers.Paddings; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Formats.Asn1; using System.Globalization; using System.IO; using System.Linq; using System.Numerics; using System.Runtime.CompilerServices; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; namespace Renci.SshNet { [System.Runtime.CompilerServices.NullableContext(1)] [System.Runtime.CompilerServices.Nullable(0)] public class PrivateKeyFile : IPrivateKeySource, IDisposable { [System.Runtime.CompilerServices.Nullable(0)] private sealed class SshDataReader : SshData { public SshDataReader(byte[] data) { Load(data); } public new uint ReadUInt32() { return base.ReadUInt32(); } public new string ReadString(Encoding encoding) { return base.ReadString(encoding); } public new byte[] ReadBytes(int length) { return base.ReadBytes(length); } public new byte[] ReadBytes() { return base.ReadBytes(); } public BigInteger ReadBigIntWithBits() { int num = (int)base.ReadUInt32(); num = (num + 7) / 8; return base.ReadBytes(num).ToBigInteger2(); } public BigInteger ReadBignum() { return base.DataStream.ReadBigInt(); } public byte[] ReadBignum2() { return ReadBinary(); } protected override void LoadData() { } protected override void SaveData() { } } private const string PrivateKeyPattern = "^-+ *BEGIN (?<keyName>\\w+( \\w+)*) *-+\\r?\\n((Proc-Type: 4,ENCRYPTED\\r?\\nDEK-Info: (?<cipherName>[A-Z0-9-]+),(?<salt>[A-F0-9]+)\\r?\\n\\r?\\n)|(Comment: \"?[^\\r\\n]*\"?\\r?\\n))?(?<data>([a-zA-Z0-9/+=]{1,80}\\r?\\n)+)(\\r?\\n)?-+ *END \\k<keyName> *-+"; private const string CertificatePattern = "(?<type>[-\\w]+@openssh\\.com)\\s(?<data>[a-zA-Z0-9\\/+=]*)(\\s+(?<comment>.*))?"; private static readonly Regex PrivateKeyRegex = new Regex("^-+ *BEGIN (?<keyName>\\w+( \\w+)*) *-+\\r?\\n((Proc-Type: 4,ENCRYPTED\\r?\\nDEK-Info: (?<cipherName>[A-Z0-9-]+),(?<salt>[A-F0-9]+)\\r?\\n\\r?\\n)|(Comment: \"?[^\\r\\n]*\"?\\r?\\n))?(?<data>([a-zA-Z0-9/+=]{1,80}\\r?\\n)+)(\\r?\\n)?-+ *END \\k<keyName> *-+", RegexOptions.Multiline | RegexOptions.ExplicitCapture | RegexOptions.Compiled); private static readonly Regex CertificateRegex = new Regex("(?<type>[-\\w]+@openssh\\.com)\\s(?<data>[a-zA-Z0-9\\/+=]*)(\\s+(?<comment>.*))?", RegexOptions.ExplicitCapture | RegexOptions.Compiled); private readonly List<HostAlgorithm> _hostAlgorithms = new List<HostAlgorithm>(); private Key _key; private bool _isDisposed; public IReadOnlyCollection<HostAlgorithm> HostKeyAlgorithms => _hostAlgorithms; public Key Key => _key; [System.Runtime.CompilerServices.Nullable(2)] [field: System.Runtime.CompilerServices.Nullable(2)] public Certificate Certificate { [System.Runtime.CompilerServices.NullableContext(2)] get; [System.Runtime.CompilerServices.NullableContext(2)] private set; } public PrivateKeyFile(Key key) { ThrowHelper.ThrowIfNull(key, "key"); _key = key; _hostAlgorithms.Add(new KeyHostAlgorithm(key.ToString(), key)); } public PrivateKeyFile(Stream privateKey) : this(privateKey, null, null) { } public PrivateKeyFile(string fileName) : this(fileName, null, null) { } public PrivateKeyFile(string fileName, [System.Runtime.CompilerServices.Nullable(2)] string passPhrase) : this(fileName, passPhrase, null) { } [System.Runtime.CompilerServices.NullableContext(2)] public PrivateKeyFile([System.Runtime.CompilerServices.Nullable(1)] string fileName, string passPhrase, string certificateFileName) { ThrowHelper.ThrowIfNull(fileName, "fileName"); using (FileStream privateKey = File.OpenRead(fileName)) Open(privateKey, passPhrase); if (certificateFileName != null) { using (FileStream certificate = File.OpenRead(certificateFileName)) OpenCertificate(certificate); } } public PrivateKeyFile(Stream privateKey, [System.Runtime.CompilerServices.Nullable(2)] string passPhrase) : this(privateKey, passPhrase, null) { } [System.Runtime.CompilerServices.NullableContext(2)] public PrivateKeyFile([System.Runtime.CompilerServices.Nullable(1)] Stream privateKey, string passPhrase, Stream certificate) { ThrowHelper.ThrowIfNull(privateKey, "privateKey"); Open(privateKey, passPhrase); if (certificate != null) OpenCertificate(certificate); } [System.Diagnostics.CodeAnalysis.MemberNotNull("_key")] private void Open(Stream privateKey, [System.Runtime.CompilerServices.Nullable(2)] string passPhrase) { Match match = default(Match); using (StreamReader streamReader = new StreamReader(privateKey)) { string input = streamReader.ReadToEnd(); match = PrivateKeyRegex.Match(input); } if (!match.Success) throw new SshException("Invalid private key file."); string text = match.Result("${keyName}"); if (!text.EndsWith("PRIVATE KEY", StringComparison.Ordinal)) throw new SshException("Invalid private key file."); string text2 = match.Result("${cipherName}"); string text3 = match.Result("${salt}"); byte[] array = Convert.FromBase64String(match.Result("${data}")); byte[] array3; if (!string.IsNullOrEmpty(text2) && !string.IsNullOrEmpty(text3)) { if (string.IsNullOrEmpty(passPhrase)) throw new SshPassPhraseNullOrEmptyException("Private key is encrypted but passphrase is empty."); byte[] array2 = new byte[text3.Length / 2]; for (int i = 0; i < array2.Length; i++) { array2[i] = Convert.ToByte(text3.Substring(i * 2, 2), 16); } CipherInfo cipherInfo; if (!(text2 == "DES-EDE3-CBC")) { if (!(text2 == "DES-EDE3-CFB")) { if (!(text2 == "DES-CBC")) { if (!(text2 == "AES-128-CBC")) { if (!(text2 == "AES-192-CBC")) { if (!(text2 == "AES-256-CBC")) throw new SshException(string.Format(CultureInfo.InvariantCulture, "Private key cipher \"{0}\" is not supported.", text2)); cipherInfo = new CipherInfo(256, (byte[] key, byte[] iv) => new AesCipher(key, iv, AesCipherMode.CBC, true), false); } else cipherInfo = new CipherInfo(192, (byte[] key, byte[] iv) => new AesCipher(key, iv, AesCipherMode.CBC, true), false); } else cipherInfo = new CipherInfo(128, (byte[] key, byte[] iv) => new AesCipher(key, iv, AesCipherMode.CBC, true), false); } else cipherInfo = new CipherInfo(64, (byte[] key, byte[] iv) => new DesCipher(key, new CbcCipherMode(iv), new PKCS7Padding()), false); } else cipherInfo = new CipherInfo(192, (byte[] key, byte[] iv) => new TripleDesCipher(key, new CfbCipherMode(iv), new PKCS7Padding()), false); } else cipherInfo = new CipherInfo(192, (byte[] key, byte[] iv) => new TripleDesCipher(key, new CbcCipherMode(iv), new PKCS7Padding()), false); array3 = DecryptKey(cipherInfo, array, passPhrase, array2); } else array3 = array; if (text != null) { switch (text.Length) { case 15: switch (text[0]) { case 'R': if (text == "RSA PRIVATE KEY") { RsaKey rsaKey3 = (RsaKey)(_key = new RsaKey(array3)); _hostAlgorithms.Add(new KeyHostAlgorithm("ssh-rsa", _key)); _hostAlgorithms.Add(new KeyHostAlgorithm("rsa-sha2-512", _key, new RsaDigitalSignature(rsaKey3, HashAlgorithmName.SHA512))); _hostAlgorithms.Add(new KeyHostAlgorithm("rsa-sha2-256", _key, new RsaDigitalSignature(rsaKey3, HashAlgorithmName.SHA256))); return; } break; case 'D': if (text == "DSA PRIVATE KEY") { _key = new DsaKey(array3); _hostAlgorithms.Add(new KeyHostAlgorithm("ssh-dss", _key)); return; } break; } break; case 14: if (text == "EC PRIVATE KEY") { _key = new EcdsaKey(array3); _hostAlgorithms.Add(new KeyHostAlgorithm(_key.ToString(), _key)); return; } break; case 11: if (text == "PRIVATE KEY") { PrivateKeyInfo privateKeyInfo = PrivateKeyInfo.GetInstance(array); _key = ParseOpenSslPkcs8PrivateKey(privateKeyInfo); RsaKey rsaKey5 = _key as RsaKey; if (rsaKey5 != null) { _hostAlgorithms.Add(new KeyHostAlgorithm("ssh-rsa", _key)); _hostAlgorithms.Add(new KeyHostAlgorithm("rsa-sha2-512", _key, new RsaDigitalSignature(rsaKey5, HashAlgorithmName.SHA512))); _hostAlgorithms.Add(new KeyHostAlgorithm("rsa-sha2-256", _key, new RsaDigitalSignature(rsaKey5, HashAlgorithmName.SHA256))); } else if (_key is DsaKey) { _hostAlgorithms.Add(new KeyHostAlgorithm("ssh-dss", _key)); } else { _hostAlgorithms.Add(new KeyHostAlgorithm(_key.ToString(), _key)); } return; } break; case 21: if (text == "ENCRYPTED PRIVATE KEY") { EncryptedPrivateKeyInfo instance = EncryptedPrivateKeyInfo.GetInstance(array); PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(passPhrase?.ToCharArray(), instance); _key = ParseOpenSslPkcs8PrivateKey(privateKeyInfo); RsaKey rsaKey4 = _key as RsaKey; if (rsaKey4 != null) { _hostAlgorithms.Add(new KeyHostAlgorithm("ssh-rsa", _key)); _hostAlgorithms.Add(new KeyHostAlgorithm("rsa-sha2-512", _key, new RsaDigitalSignature(rsaKey4, HashAlgorithmName.SHA512))); _hostAlgorithms.Add(new KeyHostAlgorithm("rsa-sha2-256", _key, new RsaDigitalSignature(rsaKey4, HashAlgorithmName.SHA256))); } else if (_key is DsaKey) { _hostAlgorithms.Add(new KeyHostAlgorithm("ssh-dss", _key)); } else { _hostAlgorithms.Add(new KeyHostAlgorithm(_key.ToString(), _key)); } return; } break; case 19: if (text == "OPENSSH PRIVATE KEY") { _key = ParseOpenSshV1Key(array3, passPhrase); RsaKey rsaKey2 = _key as RsaKey; if (rsaKey2 != null) { _hostAlgorithms.Add(new KeyHostAlgorithm("ssh-rsa", _key)); _hostAlgorithms.Add(new KeyHostAlgorithm("rsa-sha2-512", _key, new RsaDigitalSignature(rsaKey2, HashAlgorithmName.SHA512))); _hostAlgorithms.Add(new KeyHostAlgorithm("rsa-sha2-256", _key, new RsaDigitalSignature(rsaKey2, HashAlgorithmName.SHA256))); } else _hostAlgorithms.Add(new KeyHostAlgorithm(_key.ToString(), _key)); return; } break; case 26: if (text == "SSH2 ENCRYPTED PRIVATE KEY") { SshDataReader sshDataReader = new SshDataReader(array3); if (sshDataReader.ReadUInt32() != 1064303083) throw new SshException("Invalid SSH2 private key."); sshDataReader.ReadUInt32(); string text4 = sshDataReader.ReadString(SshData.Ascii); string a = sshDataReader.ReadString(SshData.Ascii); int num = (int)sshDataReader.ReadUInt32(); byte[] data; if (a == "none") data = sshDataReader.ReadBytes(num); else { if (!(a == "3des-cbc")) throw new SshException($"""{text2}"""); if (string.IsNullOrEmpty(passPhrase)) throw new SshPassPhraseNullOrEmptyException("Private key is encrypted but passphrase is empty."); data = new TripleDesCipher(GetCipherKey(passPhrase, 24), new CbcCipherMode(new byte[8]), new PKCS7Padding()).Decrypt(sshDataReader.ReadBytes(num)); } sshDataReader = new SshDataReader(data); if (sshDataReader.ReadUInt32() > num - 4) throw new SshException("Invalid passphrase."); if (text4.Contains("rsa")) { BigInteger exponent = sshDataReader.ReadBigIntWithBits(); BigInteger d = sshDataReader.ReadBigIntWithBits(); BigInteger modulus = sshDataReader.ReadBigIntWithBits(); BigInteger inverseQ = sshDataReader.ReadBigIntWithBits(); BigInteger q = sshDataReader.ReadBigIntWithBits(); BigInteger p = sshDataReader.ReadBigIntWithBits(); RsaKey rsaKey = (RsaKey)(_key = new RsaKey(modulus, exponent, d, p, q, inverseQ)); _hostAlgorithms.Add(new KeyHostAlgorithm("ssh-rsa", _key)); _hostAlgorithms.Add(new KeyHostAlgorithm("rsa-sha2-512", _key, new RsaDigitalSignature(rsaKey, HashAlgorithmName.SHA512))); _hostAlgorithms.Add(new KeyHostAlgorithm("rsa-sha2-256", _key, new RsaDigitalSignature(rsaKey, HashAlgorithmName.SHA256))); } else { if (!text4.Contains("dsa")) throw new NotSupportedException($"""{text4}"""); if (sshDataReader.ReadUInt32() != 0) throw new SshException("Invalid private key"); BigInteger p2 = sshDataReader.ReadBigIntWithBits(); BigInteger g = sshDataReader.ReadBigIntWithBits(); BigInteger q2 = sshDataReader.ReadBigIntWithBits(); BigInteger y = sshDataReader.ReadBigIntWithBits(); BigInteger x = sshDataReader.ReadBigIntWithBits(); _key = new DsaKey(p2, q2, g, y, x); _hostAlgorithms.Add(new KeyHostAlgorithm("ssh-dss", _key)); } return; } break; } } throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "Key '{0}' is not supported.", text)); } private static byte[] GetCipherKey(string passphrase, int length) { List<byte> list = new List<byte>(); using (MD5 mD = MD5.Create()) { byte[] bytes = Encoding.UTF8.GetBytes(passphrase); byte[] array = mD.ComputeHash(bytes); list.AddRange(array); while (list.Count < length) { array = bytes.Concat(array); array = mD.ComputeHash(array); list.AddRange(array); } } return list.ToArray().Take(length); } private static byte[] DecryptKey(CipherInfo cipherInfo, byte[] cipherData, string passPhrase, byte[] binarySalt) { List<byte> list = new List<byte>(); using (MD5 mD = MD5.Create()) { byte[] array = Encoding.UTF8.GetBytes(passPhrase).Concat(binarySalt.Take(8)); byte[] array2 = mD.ComputeHash(array); list.AddRange(array2); while (list.Count < cipherInfo.KeySize / 8) { array2 = array2.Concat(array); array2 = mD.ComputeHash(array2); list.AddRange(array2); } } Cipher cipher = cipherInfo.Cipher(list.ToArray(), binarySalt); try { return cipher.Decrypt(cipherData); } finally { (cipher as IDisposable)?.Dispose(); } } private unsafe static Key ParseOpenSshV1Key(byte[] keyFileData, [System.Runtime.CompilerServices.Nullable(2)] string passPhrase) { SshDataReader sshDataReader = new SshDataReader(keyFileData); ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(&global::<PrivateImplementationDetails>.E86FA4695E4C4A2E623D2981DFB47AC8C0803F2E5F2034A8067F991D8FD236CC, 15); byte[] array = sshDataReader.ReadBytes(span.Length); if (!span.SequenceEqual(array)) throw new SshException("This openssh key does not contain the 'openssh-key-v1' format magic header"); string text = sshDataReader.ReadString(Encoding.UTF8); string text2 = sshDataReader.ReadString(Encoding.UTF8); uint num = sshDataReader.ReadUInt32(); byte[] salt = null; int rounds = 0; if ((int)num > 0) { int length = (int)sshDataReader.ReadUInt32(); salt = sshDataReader.ReadBytes(length); rounds = (int)sshDataReader.ReadUInt32(); } if (sshDataReader.ReadUInt32() != 1) throw new SshException("At this time only one public key in the openssh key is supported."); sshDataReader.ReadString(Encoding.UTF8); int num2 = (int)sshDataReader.ReadUInt32(); byte[] array3 = default(byte[]); if (text != "none") { if (string.IsNullOrEmpty(passPhrase)) throw new SshPassPhraseNullOrEmptyException("Private key is encrypted but passphrase is empty."); if (string.IsNullOrEmpty(text2) || text2 != "bcrypt") throw new SshException("kdf " + text2 + " is not supported for openssh key file"); int num3 = 16; if (text != null) { CipherInfo cipherInfo; int num4; byte[] bytes; byte[] array2; byte[] arg; byte[] arg2; Cipher cipher; byte[] input; switch (text.Length) { case 10: switch (text[4]) { case '2': break; case '9': goto IL_01b0; case '5': goto IL_01d5; default: goto IL_0421; } if (!(text == "aes128-cbc")) { if (!(text == "aes128-ctr")) break; cipherInfo = new CipherInfo(128, (byte[] key, byte[] iv) => new AesCipher(key, iv, AesCipherMode.CTR, false), false); } else cipherInfo = new CipherInfo(128, (byte[] key, byte[] iv) => new AesCipher(key, iv, AesCipherMode.CBC, false), false); goto IL_0437; case 22: switch (text[3]) { case '1': break; case '2': goto IL_020f; default: goto IL_0421; } if (!(text == "aes128-gcm@openssh.com")) break; cipherInfo = new CipherInfo(128, (byte[] key, byte[] iv) => new AesGcmCipher(key, iv, 0), true); goto IL_0437; case 8: if (!(text == "3des-cbc")) break; num3 = 8; cipherInfo = new CipherInfo(192, (byte[] key, byte[] iv) => new TripleDesCipher(key, new CbcCipherMode(iv), null), false); goto IL_0437; case 29: { if (!(text == "chacha20-poly1305@openssh.com")) break; num3 = 12; cipherInfo = new CipherInfo(256, (byte[] key, byte[] iv) => new ChaCha20Poly1305Cipher(key, 0), true); goto IL_0437; } IL_01d5: if (!(text == "aes256-cbc")) { if (!(text == "aes256-ctr")) break; cipherInfo = new CipherInfo(256, (byte[] key, byte[] iv) => new AesCipher(key, iv, AesCipherMode.CTR, false), false); } else cipherInfo = new CipherInfo(256, (byte[] key, byte[] iv) => new AesCipher(key, iv, AesCipherMode.CBC, false), false); goto IL_0437; IL_020f: if (!(text == "aes256-gcm@openssh.com")) break; cipherInfo = new CipherInfo(256, (byte[] key, byte[] iv) => new AesGcmCipher(key, iv, 0), true); goto IL_0437; IL_01b0: if (!(text == "aes192-cbc")) { if (!(text == "aes192-ctr")) break; cipherInfo = new CipherInfo(192, (byte[] key, byte[] iv) => new AesCipher(key, iv, AesCipherMode.CTR, false), false); } else cipherInfo = new CipherInfo(192, (byte[] key, byte[] iv) => new AesCipher(key, iv, AesCipherMode.CBC, false), false); goto IL_0437; IL_0437: num4 = cipherInfo.KeySize / 8; bytes = Encoding.UTF8.GetBytes(passPhrase); array2 = new byte[num4 + num3]; new BCrypt().Pbkdf(bytes, salt, rounds, array2); arg = array2.Take(num4); arg2 = array2.Take(num4, num3); cipher = cipherInfo.Cipher(arg, arg2); input = sshDataReader.ReadBytes(num2 + cipher.TagSize); try { array3 = cipher.Decrypt(input, 0, num2); } finally { (cipher as IDisposable)?.Dispose(); } goto IL_04d8; } } goto IL_0421; } array3 = sshDataReader.ReadBytes(num2); goto IL_04d8; IL_0421: throw new SshException("Cipher '" + text + "' is not supported for an OpenSSH key."); IL_04d8: num2 = array3.Length; if (num2 % 8 != 0) throw new SshException("The private key section must be a multiple of the block size (8)"); SshDataReader sshDataReader2 = new SshDataReader(array3); int num5 = (int)sshDataReader2.ReadUInt32(); int num6 = (int)sshDataReader2.ReadUInt32(); if (num5 != num6) throw new SshException(string.Format(CultureInfo.InvariantCulture, "The random check bytes of the OpenSSH key do not match ({0} <-> {1}).", num5.ToString(CultureInfo.InvariantCulture), num6.ToString(CultureInfo.InvariantCulture))); string text3 = sshDataReader2.ReadString(Encoding.UTF8); Key key2; switch (text3) { case "ssh-ed25519": { sshDataReader2.ReadBignum2(); byte[] value = sshDataReader2.ReadBignum2(); key2 = new ED25519Key(value); break; } case "ecdsa-sha2-nistp256": case "ecdsa-sha2-nistp384": case "ecdsa-sha2-nistp521": { int length2 = (int)sshDataReader2.ReadUInt32(); string string = Encoding.ASCII.GetString(sshDataReader2.ReadBytes(length2)); byte[] publickey = sshDataReader2.ReadBignum2(); byte[] value = sshDataReader2.ReadBignum2(); key2 = new EcdsaKey(string, publickey, value.TrimLeadingZeros()); break; } case "ssh-rsa": { BigInteger modulus = sshDataReader2.ReadBignum(); BigInteger exponent = sshDataReader2.ReadBignum(); BigInteger d = sshDataReader2.ReadBignum(); BigInteger inverseQ = sshDataReader2.ReadBignum(); BigInteger p = sshDataReader2.ReadBignum(); BigInteger q = sshDataReader2.ReadBignum(); key2 = new RsaKey(modulus, exponent, d, p, q, inverseQ); break; } default: throw new SshException("OpenSSH key type '" + text3 + "' is not supported."); } key2.Comment = sshDataReader2.ReadString(Encoding.UTF8); byte[] array4 = sshDataReader2.ReadBytes(); for (int i = 0; i < array4.Length; i++) { if (array4[i] != i + 1) throw new SshException("Padding of openssh key format contained wrong byte at position: " + i.ToString(CultureInfo.InvariantCulture)); } return key2; } private static Key ParseOpenSslPkcs8PrivateKey(PrivateKeyInfo privateKeyInfo) { DerObjectIdentifier algorithm = privateKeyInfo.PrivateKeyAlgorithm.Algorithm; byte[] octets = privateKeyInfo.PrivateKey.GetOctets(); if (algorithm.Equals(PkcsObjectIdentifiers.RsaEncryption)) return new RsaKey(octets); if (algorithm.Equals(X9ObjectIdentifiers.IdDsa)) { AsnReader asnReader = new AsnReader(privateKeyInfo.PrivateKeyAlgorithm.Parameters.GetDerEncoded(), AsnEncodingRules.BER, default(AsnReaderOptions)); AsnReader asnReader2 = asnReader.ReadSequence(null); asnReader.ThrowIfNotEmpty(); BigInteger bigInteger = asnReader2.ReadInteger(null); BigInteger q = asnReader2.ReadInteger(null); BigInteger bigInteger2 = asnReader2.ReadInteger(null); asnReader2.ThrowIfNotEmpty(); AsnReader asnReader3 = new AsnReader(octets, AsnEncodingRules.BER, default(AsnReaderOptions)); BigInteger bigInteger3 = asnReader3.ReadInteger(null); asnReader3.ThrowIfNotEmpty(); BigInteger y = BigInteger.ModPow(bigInteger2, bigInteger3, bigInteger); return new DsaKey(bigInteger, q, bigInteger2, y, bigInteger3); } if (algorithm.Equals(X9ObjectIdentifiers.IdECPublicKey)) { AsnReader asnReader4 = new AsnReader(privateKeyInfo.PrivateKeyAlgorithm.Parameters.GetDerEncoded(), AsnEncodingRules.DER, default(AsnReaderOptions)); string curve = asnReader4.ReadObjectIdentifier(null); asnReader4.ThrowIfNotEmpty(); AsnReader asnReader5 = new AsnReader(octets, AsnEncodingRules.DER, default(AsnReaderOptions)); AsnReader asnReader6 = asnReader5.ReadSequence(null); asnReader5.ThrowIfNotEmpty(); BigInteger bigInteger4 = asnReader6.ReadInteger(null); if (bigInteger4 != BigInteger.One) throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "EC version '{0}' is not supported.", bigInteger4)); byte[] value = asnReader6.ReadOctetString(null); AsnReader asnReader7 = asnReader6.ReadSequence(new Asn1Tag(TagClass.ContextSpecific, 1, true)); int unusedBitCount = default(int); byte[] publickey = asnReader7.ReadBitString(out unusedBitCount, null); asnReader7.ThrowIfNotEmpty(); asnReader6.ThrowIfNotEmpty(); return new EcdsaKey(curve, publickey, value.TrimLeadingZeros()); } if (algorithm.Equals(EdECObjectIdentifiers.id_Ed25519)) return new ED25519Key(octets); throw new SshException(string.Format(CultureInfo.InvariantCulture, "Private key algorithm \"{0}\" is not supported.", algorithm)); } private void OpenCertificate(Stream certificate) { Match match = default(Match); using (StreamReader streamReader = new StreamReader(certificate)) { string input = streamReader.ReadToEnd(); match = CertificateRegex.Match(input); } if (!match.Success) throw new SshException("Invalid certificate file."); string s = match.Result("${data}"); Certificate = new Certificate(Convert.FromBase64String(s)); if (!Certificate.Key.Public.SequenceEqual(Key.Public)) throw new ArgumentException("The supplied certificate does not certify the supplied key."); RsaKey rsaKey = Key as RsaKey; if (rsaKey != null) { _hostAlgorithms.Insert(0, new CertificateHostAlgorithm("ssh-rsa-cert-v01@openssh.com", Key, Certificate)); _hostAlgorithms.Insert(0, new CertificateHostAlgorithm("rsa-sha2-256-cert-v01@openssh.com", Key, Certificate, new RsaDigitalSignature(rsaKey, HashAlgorithmName.SHA256))); _hostAlgorithms.Insert(0, new CertificateHostAlgorithm("rsa-sha2-512-cert-v01@openssh.com", Key, Certificate, new RsaDigitalSignature(rsaKey, HashAlgorithmName.SHA512))); } else _hostAlgorithms.Insert(0, new CertificateHostAlgorithm(Certificate.Name, Key, Certificate)); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!_isDisposed && disposing) { IDisposable disposable = _key as IDisposable; if (disposable != null) { disposable.Dispose(); _isDisposed = true; } } } } }