ras私钥c#转java_RSA:如何在Java中生成私钥并在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 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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值