在PHP上加密,但可以';t在C#上解密

本文关键字:解密 但可以 PHP 加密 | 更新日期: 2023-09-27 17:58:53

我有一个test.php,包含以下内容:

echo encrypt("something");
function encrypt($str)
{
        $enc_key = "my key is 8 char long";
        $ivArray=array( 0x10, 0x12, 5, 0x11, 0x23, 1, 0x55, 0x43 );
        $iv=null;
        foreach ($ivArray as $element)
                $iv.=CHR($element);
        return strtoupper(bin2hex(base64_encode(mcrypt_encrypt(MCRYPT_DES, $enc_key, $str, MCRYPT_MODE_CBC, $iv))));
}

然后在我的C#代码上我有:

private static byte[] iv = new byte[] { 0x10, 0x12, 5, 0x11, 0x23, 1, 0x55, 0x43 };
public string ConvertString(string input, string myKey)
{
    try
    {
        input = byteArrayString(input);
        byte[] bytes = Encoding.UTF8.GetBytes(myKey);
        byte[] buffer = Convert.FromBase64String(input);
        DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
        MemoryStream stream = new MemoryStream();
        CryptoStream stream2 = new CryptoStream(stream, provider.CreateDecryptor(bytes, iv), CryptoStreamMode.Write);
        stream2.Write(buffer, 0, buffer.Length);
        stream2.FlushFinalBlock();
        return Encoding.UTF8.GetString(stream.ToArray());
    }
    catch
    {
        return string.Empty;
    }
}
private string byteArrayString(string input)
{
    byte[] buffer = new byte[input.Length / 2];
    for (int i = 0; i < input.Length; i += 2)
    {
        if (i < input.Length)
        {
            buffer[i / 2] = (byte)((Uri.FromHex(input[i]) * 0x10) + Uri.FromHex(input[i + 1]));
        }
    }
    return Encoding.UTF8.GetString(buffer);
}

如果我在C#上完成所有操作,那么从PHP到C#的差异是从PHP得到的加密的12个字节。

为了匹配加密,我在PHP端做错了什么


更新(PKCS7):

$block = mcrypt_get_block_size('des', 'cbc');
$len = strlen($str);
$padding = $block - ($len % $block);
$str .= str_repeat(chr($padding),$padding);

在PHP上加密,但可以';t在C#上解密

在CodesInChaos的帮助下,我在php端用下面的代码解决了这个问题,以正确地填充它。

代码如果你想发布回复,我会将其标记为正确答案,否则我会标记此回复。

$block = mcrypt_get_block_size('des', 'cbc');
$len = strlen($str);
$padding = $block - ($len % $block);
$str .= str_repeat(chr($padding),$padding);
相关文章: