使用 php 进行三重 DES 加密/解密

2022-01-10 00:00:00 encryption cryptography php tripledes

我在 PHP 中有这个三重 DES 加密代码

I have this TRIPLE DES ENCRYPTION CODE IN PHP

    $encryption_key = "CE51E06875F7D964";
    $data='tokenNo=test&securityCode=111' ;
    echo $desEncryptedData = encryptText_3des($data, $encryption_key);//outputs 3des encrypted data

function encryptText_3des($plainText, $key) {
    $key = hash("md5", $key, TRUE); 
    for ($x=0;$x<8;$x++) {
        $key = $key.substr($key, $x, 1);
    }
    $padded = pkcs5_pad($plainText,
        mcrypt_get_block_size(MCRYPT_3DES, MCRYPT_MODE_CBC));
    $encrypted = base64_encode(mcrypt_encrypt(MCRYPT_3DES, $key, $padded, MCRYPT_MODE_CBC));
    return $encrypted;
}
 function pkcs5_pad ($text, $blocksize)   
{
    $pad = $blocksize - (strlen($text) % $blocksize);
    return $text . str_repeat(chr($pad), $pad);
}

我能够将数据加密为 xcFEvIdLXc2fjhG1i4iPOQu5L6ahxwZVucDOPqeMM2E=

现在我有了密钥,我可以将这些数据解密为纯文本格式吗?

Now I have the key,will I able to decrypt this data to plain text format?

我试过这样

            $encryption_key = "CE51E06875F7D964";
        $data='xcFEvIdLXc2fjhG1i4iPOQu5L6ahxwZVucDOPqeMM2E=' ; //encrypted data
        echo $desEncryptedData = encryptText_3des($data, $encryption_key);//outputs 3des encrypted data

    function encryptText_3des($plainText, $key) {
        $key = hash("md5", $key, TRUE); 
        for ($x=0;$x<8;$x++) {
            $key = $key.substr($key, $x, 1);
        }
        $padded = pkcs5_unpad($plainText,
            mcrypt_get_block_size(MCRYPT_3DES, MCRYPT_MODE_CBC));
        $encrypted = base64_encode(mcrypt_encrypt(MCRYPT_3DES, $key, $padded, MCRYPT_MODE_CBC));
        return $encrypted;
    }

    function pkcs5_unpad($text)   

    {
        $pad = ord($text{strlen($text)-1});
        if ($pad > strlen($text)) return false;
        if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) return false;
        return substr($text, 0, -1 * $pad);
    }

但我做不到.是我做错了吗?请建议我一种解密方法?加密密钥本身是否用于解密三重 DES 中的数据?请帮助

But I couldnt do it.IS what I am doing is wrong?Please suggest me a way to decrypt this?Is the encryption key itself is used to decrypt the data in triple DES?Please help

推荐答案

PHP 7.1 及以上版本,mcrypt 功能已弃用.这是使用 openssl_encrypt

For PHP 7.1 and above, mcrypt function is deprecated. Here is the alternative using openssl_encrypt

$ciphertext = openssl_encrypt('string to be encrypted', 'DES-EDE3', 'key', OPENSSL_RAW_DATA);
$ciphertext = base64_encode($ciphertext);

您可以使用此在线三重DES加密工具交叉检查.

You can use this online Triple DES encryption tool to cross check.

对于其他可用的密码,您可以调用 PHP 方法 openssl_get_cipher_methods()

For other available cipher, you can invoke PHP method openssl_get_cipher_methods()

相关文章