RSA:如何在Java中生成私钥并在C#中使用?

9

我希望在Java中生成私钥,将其保存为一个64进制编码的字符串到某个文件中,然后使用此保存的文件加密C#中的某些短语。 我知道如何在Java中生成并用64位编码加密密钥。 我的问题是如何在C#中使用此密钥? 下面是用于将私钥保存到文本文件中的Java代码原型:

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的方法。

 public static string DecryptData(string privateKey64Base, string data64Base)
 {
   // create using privateKey64Base
   // create RSACryptoServiceProvider rsa using RSAParameters above
   // byte[] encryptedData = rsa.Encrypt(Convert.FromBase64String(data64Base);
 }

我相信这个问题已经被问过了... 我只是找不到。 - Rubens Farias
2个回答

5

这个页面包含了与您的情况相关的建议,因为您正在编写PKCS#8密钥(使用keyPair.getPrivate().getEncoded())。

使用这种方法,您将在Java端使用实用程序将私钥转换为PRIVATEKEYBLOB格式。

或者,您可以使用BouncyCastle C#读取密钥(例如,参见Org.BouncyCastle.Security.PrivateKeyFactory.CreateKey - 当然,您需要先进行Base64解码)。

这个之前的问题有答案可以将BC密钥对象转换为RSACryptoServiceProvider:BouncyCastle RSAPrivateKey to .NET RSAPrivateKey

第三,您可能希望考虑使用密钥库,例如PKCS#12,这是一种更标准(和安全)的存储私钥的方式。


谢谢!你能推荐一些关于密钥库的阅读材料吗?我经常遇到它,但是我不理解这个概念。 - Moisei
+1,我几天无法访问文章,因为网站不可用,如果您可以将代码粘贴在这里或添加对更持久的网站(如Github)的引用,那将是非常好的。 - AaA

1

这是一个给询问者的示例代码:

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

感谢@peter-dettman


这个回答在过去5年里没有得到赞,但实际上非常有用,救了我的一天。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接