gpt4 book ai didi

c# - 使用 RSA/ECB/PKCS1Padding 的 .Net 加密和 java 解密

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:28:01 25 4
gpt4 key购买 nike

我们在 java 中有现有的加密代码,并且工作得非常好。我正在尝试在 .net 中创建相同的加密方法,但 java 解密方法失败,说填充错误异常。请参阅下面的代码详细信息:工作Java代码:加密:

private static byte[] doThis(String message) {
byte[] messageCrypte = null;
try {
// Certificate Input Stream
// LA SSL Certificate to be passed.
InputStream inStream = new FileInputStream(certificate);

// X509Certificate created
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) cf.generateCertificate(inStream);
inStream.close();

// Getting Public key using Certficate
PublicKey rsaPublicKey = (PublicKey) cert.getPublicKey();

Cipher encryptCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "SunJCE");
encryptCipher.init(Cipher.ENCRYPT_MODE, rsaPublicKey);

byte[] messageACrypter = message.getBytes();
// Encrypted String
messageCrypte = encryptCipher.doFinal(messageACrypter);
} catch (Exception e) {
// TODO: Exception Handling
e.printStackTrace();
}
return messageCrypte;
}

我正在尝试使用等效的 c# .Net 代码,但我从 Java 解密代码中收到错误的填充异常。

    static byte[] doThis(string message)
{
X509Certificate cert = new X509Certificate(@"C:\Data\abc-rsa-public-key-certificate.cer");
byte[] aa = cert.GetPublicKey();

RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
RSAParameters RSAKeyInfo = new RSAParameters();
byte[] Exponent = { 1, 0, 1 };

RSAKeyInfo = RSA.ExportParameters(false);
//Set RSAKeyInfo to the public key values.
RSAKeyInfo.Modulus = aa;
//RSAKeyInfo.Exponent = Exponent;
RSA.ImportParameters(RSAKeyInfo);
byte[] bb = RSA.Encrypt(GetBytes(message), false);
return bb;
}

Java解密代码

private String getDecryptedString(byte[] credentials, PrivateKey secretKey) throws NoSuchAlgorithmException,
NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException,
BadPaddingException {
String decryptedString;
Cipher decryptCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "SunJCE");
decryptCipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] messageDecrypte = decryptCipher.doFinal(credentials);
decryptedString = new String(messageDecrypte);
return decryptedString;
}

最佳答案

这是 .net 代码:

public static string EncrypIt(string inputString, X509Certificate2 cert)
{
RSACryptoServiceProvider rsaservice = (RSACryptoServiceProvider)cert.PublicKey.Key;
byte[] plaintext = Encoding.UTF8.GetBytes(inputString);
byte[] ciphertext = rsaservice.Encrypt(plaintext, false);
string cipherresult = Convert.ToBase64String(ciphertext);
return cipherresult;
}

关于c# - 使用 RSA/ECB/PKCS1Padding 的 .Net 加密和 java 解密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18871770/

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