简体   繁体   中英

Encrypting on PHP but can't decrypt on C#

I have a test.php with the following:

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))));
}

Then on my C# code I have:

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);
}

If I do it all on C# it works the difference from the PHP to the C# is 12 bytes on the resulting encryption from the PHP.

What am I doing wrong at the PHP side to match the encryption ?


Update (PKCS7):

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

With CodesInChaos help I've solved it with the below code on the php side to correctly pad it.

CodesInChaos if u feel like posting a reply I will mark it as the right answer otherwise I will mark this one instead.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM