使用3des算法,加密模式:CBC,填充:pkcs5padding
/*** 3DES加解密类*/
class Des3phpService
{//加密秘钥(base64加密)private $key ;//初始偏移向量private $iv;/*** 构造,传递二个已经进行base64_encode的KEY与IV** @param string $key* @param string $iv*/public function __construct($key, $iv){$this->iv = $iv;$this->key = $key;}//填充加密快的大小public function pkcs5_pad($text, $blocksize){$padding_char = $blocksize - (strlen($text) % $blocksize);$text .= str_repeat(chr($padding_char), $padding_char);return $text;}//解密public function decrypt($encrypted){$key = $this->key;$encrypted = base64_decode($encrypted);$size = openssl_cipher_iv_length("DES-EDE3-CBC");if ($this->iv == "") {$iv = openssl_random_pseudo_bytes($size);} else {$iv = $this->iv;}$rs = openssl_decrypt($encrypted, "DES-EDE3-CBC", $key, OPENSSL_RAW_DATA | OPENSSL_NO_PADDING, $iv);$rs = $this->pkcs5_unpad($rs);return $rs;}//加密public function encrypt($input){$key =$this->key;$size = openssl_cipher_iv_length("DES-EDE3-CBC");$input = $this->pkcs5_pad($input, $size);$rs = openssl_encrypt($input, "DES-EDE3-CBC", $key, OPENSSL_RAW_DATA | OPENSSL_NO_PADDING, $this->iv);$rs = base64_encode($rs);return $rs;}public 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);}
}
$key = 'abcdefgh12345678abcdefgh';
$iv = '12345678';
$des = new Des3phpService($key, $iv);
$str = "api";
echo "source: {$str},len: ", strlen($str), "\r\n";
$e_str = $des->encrypt($str);
echo "entrypt: ", $e_str, "\r\n";
$d_str = $des->decrypt($e_str);
echo "dntrypt: {$d_str},len: ", strlen($d_str), "\r\n";
# 明文='api';
# 密文='eH89ioIVp/Y='
作者:双月鸟
链接:https://www.jianshu.com/p/047cfee4990f
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。