PHP实现3DES加密解密

Ezra
2023-10-08 / 0 评论 / 276 阅读 / 正在检测是否收录...
<?php
class TripleDES{
    /**
     * 3des加密
     * @param string $str 需要加密的字符串
     * @param string $key 秘钥24位
     * @return string
     */
    public static function encrypt($str,$key){
        $str = self::pkcs5_pad($str, 8);
        if (strlen($str) % 8) {
            $str = str_pad($str, strlen($str) + 8 - strlen($str) % 8, "\0");
        }
        $sign = openssl_encrypt($str, 'DES-EDE3', $key, OPENSSL_RAW_DATA | OPENSSL_NO_PADDING, '');
        return base64_encode($sign);
    }

    /**
     * 3des解密
     * @param string $str 需要加密的字符串
     * @param string $key 秘钥24位
     * @return string
     */
    public static function decrypt($str,$key) {
        $decrypted = openssl_decrypt(base64_decode($str), 'DES-EDE3', $key, OPENSSL_RAW_DATA,'');
        return $decrypted;
    }
 
    //填充模式pkcs5padding
    private static function pkcs5_pad($text, $blocksize) {
        $pad = $blocksize - (strlen($text) % $blocksize);
        return $text . str_repeat(chr($pad), $pad);
    }
 
}
 
// echo TripleDES::encrypt('123456', '9oyKs7cVo1yYzkuisP9bhA=='); // 结果:ha3MLQ7hjao=
// echo TripleDES::decrypt('ha3MLQ7hjao=', '9oyKs7cVo1yYzkuisP9bhA=='); // 结果:ha3MLQ7hjao=
?>
0

评论 (0)

取消