使用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='