views:

561

answers:

1

I would like to generate private key in java, save it as a 64 base encoded string in some file and then encrypt some phrase in C# using this saved file. I know to generate keys in java and encode it with 64 base. My question is how do I use this key in C#? This is a java code prototype to save private key into text file:

KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
RSAKeyGenParameterSpec spec = new RSAKeyGenParameterSpec(1024, RSAKeyGenParameterSpec.F4);
keyGen.initialize(spec);
KeyPair keyPair = keyGen.generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
writeToFile("privateKey", Base64.encode(keyPair.getPrivate().getEncoded()));

I would like to implement following function in C# but can't find how to create RSAParameters or RSACryptoServiceProvider from private key

 public static string DecryptData(string privateKey64Base, string data64Base)
 {
   // create using privateKey64Base
   // create RSACryptoServiceProvider rsa using RSAParameters above
   // byte[] encryptedData = rsa.Encrypt(Convert.FromBase64String(data64Base);
 }
+2  A: 

This page contains advice for your situation, since you are writing out PKCS#8 keys (with keyPair.getPrivate().getEncoded()): [http://www.jensign.com/JavaScience/PvkConvert/][1]

Using this approach you would use the utility on the Java side to get the private key into the PRIVATEKEYBLOB format in the first place.

Alternatively, you could use BouncyCastle C# which can read the key in (see e.g. Org.BouncyCastle.Security.PrivateKeyFactory.CreateKey - you'd need to Base64 decode first of course).

This previous question has the answer for converting from the resulting BC key object to RSACryptoServiceProvider: http://stackoverflow.com/questions/949727/bouncycastle-rsaprivatekey-to-ms-net-rsaprivatekey-c

Thirdly, you might want to look at using a keystore, e.g. PKCS#12, which is a more standard (and secure) way for storing private keys.

Peter Dettman
Thanks! Could you recommend any reading on keystore? I meet it quite often but I don't understand the concept.
Moisei