0

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
Chris
  • 11
  • 5
  • May I suggest using an actual Xml Parser/Builder instead of making your own xml string? Building your own is a terrible idea that can lead to many software bugs. – gunr2171 May 28 '14 at 20:37

1 Answers1

2

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);
Orogenesis
  • 61
  • 2