欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

php des加解密类封装

程序员文章站 2024-03-14 13:21:04
...

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

相关标签: php 加密解密