C# RSA FromXmlString() 错误数据异常 [英] C# RSA FromXmlString() BadData Exception

查看:350
本文介绍了C# RSA FromXmlString() 错误数据异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我像这样生成一个密钥:

I generate a key like so:

ssh-keygen -t rsa1 -b 768 -C 测试

ssh-keygen -t rsa1 -b 768 -C Test

我得到一个如下所示的公钥:

I get a public key that looks like:

768 655371244818534536334574875801623177648392314095757825816788136360615069738317432684324135107640137961040160008388231420349935694006787032419425836353385388446738225464450963417153771331511902010734528761152834146019053540579969112124269测试

768 65537 1244818534536334574875801623177648392314095757825816788136360615069738317432684324135107640137961040160008388231420349935694006787032419425836353385388446738225464450963417153771331511902010734528761152834146019053540579969112124269 Test

我在导入公钥时遇到问题.据我所知,以下应该有效.对 FromXmlString() 的调用因 BadData 加密异常而失败.我不确定我做错了什么.

I'm having issues with importing a public key. As far as I'm aware the below should work. The call to FromXmlString() fails with BadData crypto exception. I'm not sure what I'm doing wrong.

string rsaKeyValue = "<RSAKeyValue>";
rsaKeyValue += "<Modulus>";
rsaKeyValue += Convert.ToBase64String(Encoding.ASCII.GetBytes(openSSHKeySplit[2]));
rsaKeyValue += "</Modulus>";
rsaKeyValue += "<Exponent>";
rsaKeyValue += Convert.ToBase64String(Encoding.ASCII.GetBytes(openSSHKeySplit[1]));
rsaKeyValue += "</Exponent>";
rsaKeyValue += "</RSAKeyValue>";                
mRSAContext.FromXmlString(rsaKeyValue); // This throws a BadData Crypto Exception

推荐答案

您需要将数字解释为实际数字,而不是十进制 ascii 数字流.例如,对于指数,您当前正在获取 ascii 字节流 (0x36 0x35 0x35 0x33 0x37) 的 base64,而您应该使用 int.Parse("65537") 将其转换为整数,然后获取在传递给 base64 编码器之前使用 BitConverter.GetBytes() 的字节数组.模数有点棘手,因为它比标准整数大.您可以尝试 System.Numerics 中的 BigInteger 类.即,BigInteger.Parse("");

You need to interpret the numbers as actual numbers instead of a stream of decimal ascii digits. For instance, for the exponent, you're currently getting the base64 of the stream of ascii bytes (0x36 0x35 0x35 0x33 0x37), whereas you should convert it to an integer with int.Parse("65537"), and then get the byte array using BitConverter.GetBytes() before passing to the base64 encoder. The modulus is a bit trickier since it's larger than will fit into a standard integer. You could try the BigInteger class from System.Numerics. Ie, BigInteger.Parse("");

注意,您不必制作自己的 XML 字符串.我相信您可以使用 RSACryptoServiceProvider 和 RSAParameters 对象来实现相同的目标.

Note, you don't have to make your own XML string. I believe you can use the RSACryptoServiceProvider along with an RSAParameters object to accomplish the same goal.

RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
RSAParameters parameters = new RSAParameters();
parameters.Modulus = mod; // Your calculated modulus
parameters.Exponent = exp; // Your calculated exponent
rsa.ImportParameters(parameters);

这篇关于C# RSA FromXmlString() 错误数据异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆