C#读取ssh-keygen生成的id_rsa.pub格式的密钥
public static RSACryptoServiceProvider DecodeX509PublicKey(string key)
{
byte[] raw = Convert.FromBase64String(key);
var mem = new MemoryStream(raw);
var br = new BinaryReader(mem);
List<byte[]> buffers = new List<byte[]>();
while (true)
{
var data = br.ReadBytes(4);
if (data.Length < 4) break;
Array.Reverse(data);
int len = BitConverter.ToInt32(data, 0);
byte[] part = br.ReadBytes(len);
buffers.Add(part);
}
if (buffers.Count != 3) return null;
byte[] mod = buffers[2];
if (mod[0] == 0)
mod = mod.Skip(1).Take(mod.Length - 1).ToArray();
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
RSAParameters rsaKeyInfo = new RSAParameters
{
Modulus = mod,
Exponent = buffers[1]
};
rsa.ImportParameters(rsaKeyInfo);
return rsa;
}