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);
}
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.
Generate RSA Key Pair We can easily do it by using the KeyPairGenerator from java. security package: KeyPairGenerator generator = KeyPairGenerator. getInstance("RSA"); generator.
Store/Retrieve Private Key/Public Key to/from disk/file :D. PrivateKey privateKey = keyPair. getPrivate(); PublicKey publicKey = keyPair.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With