gpt4 book ai didi

C# 使用 RSA 加密 PHP 解密

转载 作者:太空宇宙 更新时间:2023-11-03 13:44:37 30 4
gpt4 key购买 nike

我正在尝试在 C# 和 PHP 之间构建一个简单的 RSA 加密解密过程。我已经使用 phpseclib( http://phpseclib.sourceforge.net/ ) 在 PHP 中完成了加密,在 C# 中完成了解密。但是我越来越“第 2103 行 C:\xampp\htdocs\Crypt\RSA.php 中的解密错误”这是这部分:

if ($lHash != $lHash2) {
user_error('Decryption error', E_USER_NOTICE);
return false;
}

C#中的加密我用了这串代码:

RSACryptoServiceProvider rsaCryptoServiceProvider = new RSACryptoServiceProvider(dwKeySize);
rsaCryptoServiceProvider.FromXmlString(publickey);
int keySize = dwKeySize / 8;
byte[] bytes = Encoding.UTF32.GetBytes(inputString);
// The hash function in use by the .NET RSACryptoServiceProvider here is SHA1
// int maxLength = ( keySize ) - 2 - ( 2 * SHA1.Create().ComputeHash( rawBytes ).Length );
int maxLength = keySize - 42;
int dataLength = bytes.Length;
int iterations = dataLength / maxLength;
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i <= iterations; i++)
{
byte[] tempBytes = new byte[(dataLength - maxLength * i > maxLength) ? maxLength : dataLength - maxLength * i];
Buffer.BlockCopy(bytes, maxLength * i, tempBytes, 0, tempBytes.Length);
byte[] encryptedBytes = rsaCryptoServiceProvider.Encrypt(tempBytes, true);
// Be aware the RSACryptoServiceProvider reverses the order of encrypted bytes after encryption and before decryption.
// If you do not require compatibility with Microsoft Cryptographic API (CAPI) and/or other vendors.
// Comment out the next line and the corresponding one in the DecryptString function.
Array.Reverse(encryptedBytes);
// Why convert to base 64?
// Because it is the largest power-of-two base printable using only ASCII characters
stringBuilder.Append(Convert.ToBase64String(encryptedBytes));
}
string ciphertext = stringBuilder.ToString();

和我要解密的基本 PHP 代码:

$rsa->loadKeyfromXML($privatekey);  
$ciphertext = file_get_contents('cipher.txt');
$ciphertext = base64_decode(strrev($ciphertext));

//$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);

$plaintext = $rsa->decrypt($ciphertext);

我已经尝试过 PKC1,它还在 Crypt/RSA.php 中给出了另一个错误

最佳答案

是的,我刚刚自己找到了解决方案。我更改了加密行:

byte[] bytes = Encoding.UTF32.GetBytes(inputString);  ==> byte[] bytes = Encoding.Default.GetBytes(inputString);

也正如@Ryan所说:

$ciphertext = base64_decode(strrev($ciphertext));  ==> $ciphertext = strrev(base64_decode($ciphertext));

感谢您的尝试。

关于C# 使用 RSA 加密 PHP 解密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15791890/

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