gpt4 book ai didi

java - 将 Java.Security.KeyPair 转换为 .NET RSACryptoServiceProvider

转载 作者:行者123 更新时间:2023-11-29 21:12:59 29 4
gpt4 key购买 nike

我如何编码 Java 生成的 RSA 私钥(和公钥),以便它可以在 .NET 中解码以在 RSACryptoServiceProvider 中使用?

我试过这段代码:

var keyGen = KeyPairGenerator.GetInstance("RSA");
keyGen.Initialize(2048);
KeyPair keyPair = keyGen.GenerateKeyPair();

IPrivateKey privateKey = keyPair.Private;
byte[] nativePrivateKey = privateKey.GetEncoded();

var nativeToRsa = new RSACryptoServiceProvider();
nativeToRsa.ImportCspBlob(nativePrivateKey); // throws a CryptographicException

我正在使用 Xamarin.Android 编写 C#,但“ native ”Java RSA key 生成器比单声道生成器快很多。所以我想使用 Java,但我仍然需要能够与 Windows 人员交换公钥和/或私钥,以便与 RSACryptoServiceProvider 一起使用。

因此,最终我可能希望/需要采用两种方式(Java<->RSACryptoServiceProvider)。有没有人有任何指示?

谢谢。

最佳答案

C# 从 xml 函数加载 RSA 加密提供程序。试试下面的方法:

Java

                KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(1024);
KeyPair keyPair = keyGen.generateKeyPair();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
BigInteger mod_Int = publicKey.getModulus();
BigInteger exp_Int = publicKey.getPublicExponent();
byte[] mod_Bytes_Extra = mod_Int.toByteArray();
byte[] mod_Bytes = new byte[128];
System.arraycopy(mod_Bytes_Extra, 1, mod_Bytes, 0, 128);
byte[] exp_Bytes = exp_Int.toByteArray();
String modulus = Base64.encodeToString(mod_Bytes, Base64.DEFAULT);
String exponent = Base64.encodeToString(exp_Bytes, Base64.DEFAULT);
System.out.println(modulus);
System.out.println(exponent);
String public_Xml = "<BitStrength>0124</BitStrength><RSAKeyValue><Modulus>"+modulus+"</Modulus><Exponent>"+exponent+"</Exponent></RSAKeyValue>";

C#

class KeyBuilder
{
private RSACryptoServiceProvider rsa;

public RSACryptoServiceProvider CreateKey(string rsaKeyPair)
{
rsa = new RSACryptoServiceProvider();
StringBuilder output = new StringBuilder();
string xmlString = "<Key>" + rsaKeyPair + "</Key>";
rsa.FromXmlString(xmlString);
return rsa;
}
}

始终让您在 Java 端使用 UTF-8 编码读取/写入字节数组,因为 Java 默认使用 Unicode 编码,而 C# 使用 UTF-8。

Java 中的字节数组也是有符号的,而在 C# 中它们是无符号的。因此,如果您必须在 C# 端解析从 Java 代码发送的二进制数据,请在 sbyte 数组中读取它。

关于java - 将 Java.Security.KeyPair 转换为 .NET RSACryptoServiceProvider,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22214966/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com