Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RSA: How to generate private key in java and use it in C#?

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);
 }
like image 778
Moisei Avatar asked Feb 02 '10 15:02

Moisei


People also ask

What do I do with my RSA private key?

The RSA private key is used to generate digital signatures, and the RSA public key is used to verify digital signatures. The RSA public key is also used for key encryption of DES or AES DATA keys and the RSA private key for key recovery.

How do you generate an RSA KeyPair in Java?

Generate RSA Key Pair We can easily do it by using the KeyPairGenerator from java. security package: KeyPairGenerator generator = KeyPairGenerator. getInstance("RSA"); generator.

How do I save a private key in Java?

Store/Retrieve Private Key/Public Key to/from disk/file :D. PrivateKey privateKey = keyPair. getPrivate(); PublicKey publicKey = keyPair.


1 Answers

This page contains advice for your situation, since you are writing out PKCS#8 keys (with keyPair.getPrivate().getEncoded())

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: BouncyCastle RSAPrivateKey to .NET RSAPrivateKey

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.

like image 65
Peter Dettman Avatar answered Sep 23 '22 20:09

Peter Dettman