我正在尝试在C#和PHP之间构建一个简单的RSA加密解密过程。
我已经使用phpseclib(http://phpseclib.sourceforge.net/)完成了PHP中的加密和C#中的解密。然而,我遇到了“Decryption error in C:\xampp\htdocs\Crypt\RSA.php on line 2103”错误,它在此处:
我尝试过PKC1,但在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中出现了另一个错误。