PHP中的c# TripleDES ECB加密


C# TripleDES ECB Encryption in PHP

我主要使用PHP工作,但我将数据发送到使用c#加密的api,所以我试图在PHP中加密密码,使用以下c#代码中使用的相同方法:

System.Security.Cryptography.TripleDESCryptoServiceProvider DES = new System.Security.Cryptography.TripleDESCryptoServiceProvider();
System.Security.Cryptography.MD5CryptoServiceProvider hashMD5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
DES.Key = hashMD5.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(Key));
DES.Mode = System.Security.Cryptography.CipherMode.ECB;
System.Security.Cryptography.ICryptoTransform DESEncrypt = DES.CreateEncryptor();
Buffer = System.Text.ASCIIEncoding.ASCII.GetBytes(Plaintext);
string TripleDES = Convert.ToBase64String(DESEncrypt.TransformFinalBlock(Buffer, 0, Buffer.Length));
return TripleDES;

这是我目前在PHP中写的:

    function encryptData($key, $plainText)
    {
        $byte = mb_convert_encoding($key, 'ASCII');
        $desKey = md5(utf8_encode($byte), true);
        $data = mb_convert_encoding($plainText, 'ASCII');
        // add PKCS#7 padding
        $blocksize = mcrypt_get_block_size('tripledes', 'ecb');
        $paddingSize = $blocksize - (strlen($data) % $blocksize);
        $data .= str_repeat(chr($paddingSize), $paddingSize);
        // encrypt password
        $encData = mcrypt_encrypt('tripledes', $desKey, $data, 'ecb');
        echo base64_encode($encData);
    }

我知道我需要为md5函数添加true参数,并且我知道我需要添加PKCS7填充。

我还没有机会检查它与c#代码,因为我还在我的电脑上安装visual studio。我错过什么了吗?我需要加静脉注射吗?

编辑:我测试了c#代码,看到它没有给出相同的结果。我修复了一些东西,现在PHP中有c#中的DES.Key和Buffer变量,给出了正确的结果。

再次编辑:已修复。我所要做的就是将前8个字符附加到散列键的末尾。

$desKey .= substr($desKey,0,8);

这是我最终想到的。到目前为止,在我尝试过的几个例子中,它对我来说是有效的。

function encryptData($key, $plainText)
{
    $byte = mb_convert_encoding($key, 'ASCII');
    $desKey = md5(utf8_encode($byte), true);
    $desKey .= substr($desKey,0,8);
    $data = mb_convert_encoding($plainText, 'ASCII');
    // add PKCS#7 padding
    $blocksize = mcrypt_get_block_size('tripledes', 'ecb');
    $paddingSize = $blocksize - (strlen($data) % $blocksize);
    $data .= str_repeat(chr($paddingSize), $paddingSize);
    // encrypt password
    $encData = mcrypt_encrypt('tripledes', $desKey, $data, 'ecb');
    echo base64_encode($encData);
}
encryptData('key', 'pass');