9

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);
 }
Moisei
  • 1,162
  • 13
  • 30

2 Answers2

5

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.

Community
  • 1
  • 1
Peter Dettman
  • 3,867
  • 20
  • 34
  • Thanks! Could you recommend any reading on keystore? I meet it quite often but I don't understand the concept. – Moisei Feb 03 '10 at 09:08
  • +1, I couldn't access article for few days because website wasn't available, it would be great if you could paste the code in here or add a reference to more persistent websites such as Github. – AaA Aug 17 '17 at 10:15
0

here is a sample code for whom asked:

AsymmetricKeyParameter keyPair = Org.BouncyCastle.Security.PrivateKeyFactory.CreateKey(Convert.FromBase64String("PKCS#8Key"));
var decryptEngine = new Pkcs1Encoding(new RsaEngine());
decryptEngine.Init(false, keyPair);
var decrypted = Encoding.UTF8.GetString(decryptEngine.ProcessBlock(bytesToDecrypt, 0, bytesToDecrypt.Length));

credit to @peter-dettman

Jean-François Corbett
  • 37,420
  • 30
  • 139
  • 188
aabdan
  • 111
  • 2
  • 5