public static SSH2UserAuthKey FromSECSHStyleStream(Stream strm, string passphrase)
{
StreamReader r = new StreamReader(strm, Encoding.ASCII);
string l = r.ReadLine();
if (l == null || l != "---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----")
throw new SSHException("Wrong key format");
string comment = "";
l = r.ReadLine();
StringBuilder buf = new StringBuilder();
while (l != "---- END SSH2 ENCRYPTED PRIVATE KEY ----") {
if (l.IndexOf(':') == -1)
buf.Append(l);
else if (l[l.Length - 1] == '\\')
buf.Append(l, 0, l.Length - 1);
else if (l.StartsWith("Comment: "))
comment = l.Substring("Comment: ".Length);
l = r.ReadLine();
if (l == null)
throw new SSHException("Key is broken");
}
r.Close();
byte[] keydata = Base64.Decode(Encoding.ASCII.GetBytes(buf.ToString()));
//Debug.WriteLine(DebugUtil.DumpByteArray(keydata));
SSH2DataReader re = new SSH2DataReader(keydata);
int magic = re.ReadInt32();
if (magic != MAGIC_VAL)
throw new SSHException("key file is broken");
int privateKeyLen = re.ReadInt32();
string type = Encoding.ASCII.GetString(re.ReadString());
string ciphername = Encoding.ASCII.GetString(re.ReadString());
int bufLen = re.ReadInt32();
if (ciphername != "none") {
CipherAlgorithm algo = CipherFactory.SSH2NameToAlgorithm(ciphername);
byte[] key = PassphraseToKey(passphrase, CipherFactory.GetKeySize(algo));
Cipher c = CipherFactory.CreateCipher(SSHProtocol.SSH2, algo, key);
byte[] tmp = new Byte[re.Image.Length - re.Offset];
c.Decrypt(re.Image, re.Offset, re.Image.Length - re.Offset, tmp, 0);
re = new SSH2DataReader(tmp);
}
int parmLen = re.ReadInt32();
if (parmLen < 0 || parmLen > re.Rest)
throw new SSHException(Strings.GetString("WrongPassphrase"));
if (type.IndexOf("if-modn") != -1) {
//mindterm mistaken this order of BigIntegers
BigInteger e = re.ReadBigIntWithBits();
BigInteger d = re.ReadBigIntWithBits();
BigInteger n = re.ReadBigIntWithBits();
BigInteger u = re.ReadBigIntWithBits();
BigInteger p = re.ReadBigIntWithBits();
BigInteger q = re.ReadBigIntWithBits();
return new SSH2UserAuthKey(new RSAKeyPair(e, d, n, u, p, q), comment);
}
else if (type.IndexOf("dl-modp") != -1) {
if (re.ReadInt32() != 0)
throw new SSHException("DSS Private Key File is broken");
BigInteger p = re.ReadBigIntWithBits();
BigInteger g = re.ReadBigIntWithBits();
BigInteger q = re.ReadBigIntWithBits();
BigInteger y = re.ReadBigIntWithBits();
BigInteger x = re.ReadBigIntWithBits();
return new SSH2UserAuthKey(new DSAKeyPair(p, g, q, y, x), comment);
}
else
throw new SSHException("unknown authentication method " + type);
}