4

我有一个带有以下内容的 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);
4

1 回答 1

1

在 CodesInChaos 的帮助下,我在 php 端使用以下代码解决了它,以正确填充它。

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

$block = mcrypt_get_block_size('des', 'cbc');
$len = strlen($str);
$padding = $block - ($len % $block);
$str .= str_repeat(chr($padding),$padding);
于 2013-02-14T14:10:56.100 回答