c#加密PHP解密使用RSA


C# encrypt PHP decrypt using RSA

我试图在c#和PHP之间建立一个简单的RSA加密解密过程。我已经完成了加密在PHP和解密在c#与phpseclib(http://phpseclib.sourceforge.net/)。然而,我得到" C:'xampp'htdocs'Crypt'RSA.php在2103行的解密错误",即这部分:

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#中做Array.Reverse,我猜strrev在PHP中是不必要的。

另外,phpseclib的Crypt_RSA没有loadKeyfromXML。你从哪知道的?做$rsa->loadKey()就足够了。

最后,我猜PKCS1是必需的。当你使用它时,你得到的错误是什么?

在我看来,在PHP中,你正在采取base64编码的密文,逆转,然后尝试base64解码它?我认为你应该先解码,然后再反转结果。它们不是一回事。

这种逆转是否有必要摆在首位,我不能说。

我不得不说我没有完全得到你的问题,但它似乎是如何结合RSA加密在c#和PHP。我也遇到了一些麻烦,对于每个仍然感兴趣的人,我写了一个工作项目来做这件事,c#程序和PHP脚本都创建RSA密钥并交换它们,然后加密通信(见这里)。