RSA:如何在Java中生成私钥并在C#中使用它? [英] RSA: How to generate private key in java and use it in C#?

查看:481
本文介绍了RSA:如何在Java中生成私钥并在C#中使用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在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#中使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆