php des加解密类封装

php des加解密类封装

<?php
namespace Des;
class JoDES
{
    public $key;
    public $iv;

    function __construct($key) {
        $this->key = $key;
        $this->iv = '';
    }


    /**
     * DES 解密函数
     *
     * @param  string $ciphertext 密文
     * @param  string $method 加密方式
     * @param  string $password 密钥
     */
    function decrypt($ciphertext, $method = 'DES-ECB', $options = OPENSSL_ZERO_PADDING) {
        $password = $this->key;
        $hex = hex2bin($ciphertext);
        $data = base64_encode($hex);
        $plaintext = openssl_decrypt($data, $method, $password, $options);
        return trim($plaintext);
    }

    /**
     * DES 加密函数
     *
     * @param  string $plaintext 明文
     * @param  string $method 解密方式
     * @param  string $password 密钥
     */
    function encrypt($plaintext, $method = 'DES-ECB', $options = OPENSSL_ZERO_PADDING) {
        return strtoupper(bin2hex(mcrypt_encrypt(MCRYPT_DES, $this->key, $plaintext,'ecb', $this->iv)));
        $password = $this->key;
        //字符串长度要求是8的倍数,不够要空值补足
        if ($m = strlen($plaintext) % 8) {
            $plaintext .= str_repeat("\x00", 8 - $m);//双字节字符
        }

        $encResult = openssl_encrypt($plaintext, $method, $password, $options);
        $ciphertext = bin2hex(base64_decode($encResult));
        return $ciphertext;
    }

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


    function strToHex($string) {
        $hex = "";
        for ($i = 0; $i < strlen($string); $i++)
            $hex .= dechex(ord($string[$i]));
        $hex = strtoupper($hex);
        return $hex;
    }

    function hexToStr($hex) { //十六进制转字符串
        $string = "";
        for ($i = 0; $i < strlen($hex) - 1; $i += 2)
            $string .= chr(hexdec($hex[$i] . $hex[$i + 1]));
        return $string;
    }
}

注:mcrypt_encrypt()函数在php5.6版本不再接受解密key后面补\0的做法,如果位数不足8位,会返回false

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值