简体   繁体   中英

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

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 eg 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, eg PKCS#12, which is a more standard (and secure) way for storing private keys.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM