首页  编辑  

C#读取openssh生成的密钥

Tags: /C#/算法/   Date Created:
C#读取ssh-keygen生成的id_rsa.pub格式的密钥
/// <summary>
/// 解码ssh-keygen生成的id_rsa.pub格式的数据:
/// ssh-rsa AAAAB3NzaC1....TkGdVdhwdLJMI2B4KUyMf+Q== abc@demo
/// 其中AAA到==之间为Base64编码,按Base64解码即可,解码后的数据格式
/// 4字节长度 + 数据1 + 4字节长度 + 数据2 + 4字节长度 + 数据3
/// 数据1为TAG,固定为ssh-rsa或者ssh-dsa
/// 数据2为Exponent的字节流
/// 数据3为Modulus的字节流
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
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;
}