C# RSA FromXmlString() BadData Exception

自闭症网瘾萝莉.ら 提交于 2021-01-29 15:45:27

问题


I generate a key like so:

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

I get a public key that looks like:

768 65537 1244818534536334574875801623177648392314095757825816788136360615069738317432684324135107640137961040160008388231420349935694006787032419425836353385388446738225464450963417153771331511902010734528761152834146019053540579969112124269 Test

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

回答1:


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("");

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);


来源:https://stackoverflow.com/questions/23921323/c-sharp-rsa-fromxmlstring-baddata-exception

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!