我想在java中生成私钥,将其保存为某些文件中的64基本编码字符串,然后使用此保存的文件在C#中加密一些短语。 我知道在java中生成密钥并用64基数编码。 我的问题是如何在C#中使用这个键? 这是一个将代码保存到文本文件中的java代码原型:
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()));我想在C#中实现以下函数,但是找不到如何创建RSAParameters或 RSACryptoServiceProvider from private key
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); }推荐答案
此页面包含您的情况的建议,因为您正在写出PKCS#8键(与keyPair.getPrivate()。getEncoded())
This page contains advice for your situation, since you are writing out PKCS#8 keys (with keyPair.getPrivate().getEncoded())
使用这种方法,您将使用Java端的实用程序首先将私钥获取为PRIVATEKEYBLOB格式。
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.
,你可以使用BouncyCastle C#,它可以读取密钥(见例如
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).
这个上一个问题的答案是从生成的BC密钥转换成的对象到RSACryptoServiceProvider: BouncyCastle RSAPrivateKey到.NET RSAPrivateKey
This previous question has the answer for converting from the resulting BC key object to RSACryptoServiceProvider: BouncyCastle RSAPrivateKey to .NET RSAPrivateKey
第三,你可能想查看使用密钥库,例如PKCS#12,这是一种更标准(和安全)的存储私钥的方式。
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.
更多推荐
RSA:如何在Java中生成私钥并在C#中使用它?
发布评论