我正在尝试在 C# 和 PHP 之间构建一个简单的 RSA 加密解密过程。我已经使用 phpseclib( http://phpseclib.sourceforge.net/ ) 完成了 PHP 中的加密和 C# 中的 decrpyt。但是,我在第 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 代码来 decrpyt:
$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 中给出了另一个错误