CBC模式一定要指定IV加密向量
ECB模式不需要指定IV加密向量
class TripleDes {
/**
* @var string
*/
var $key = '';
/**
* @var string
*/
var $iv = '';
/**
* Des3 constructor.
* @param string|null $key
* @param string|null $iv
*/
public function __construct(string $key=null, string $iv=null)
{
if (!$key && strlen($key) != 24) {
throw new \Exception("3DES_KEY长度错误,长度为24");
}
if (!$iv && strlen($iv) != 8) {
throw new \Exception("3DES_IV长度错误,长度为8");
}
$this->key = $key;
$this->iv = $iv;
}
public function encrypt($input, $key='', $iv='') {
$this->key = $key ? $key : $this->key;
$this->iv = $iv ? $iv : $this->iv;
//return base64_encode(openssl_encrypt($input, "des-ede3-cbc", $this->key, OPENSSL_RAW_DATA, $this->iv));
return base64_encode(openssl_encrypt($input, "des-ede3", $this->key, OPENSSL_RAW_DATA));
}
public function decrypt($encrypted, $key='', $iv='') {
$this->key = $key ? $key : $this->key;
$this->iv = $iv ? $iv : $this->iv;
//return openssl_decrypt(base64_decode($encrypted), 'des-ede3-cbc', $this->key, OPENSSL_RAW_DATA, $this->iv);
return openssl_decrypt(base64_decode($encrypted), 'des-ede3', $this->key, OPENSSL_RAW_DATA);
}
}
注意:(1)3DES密钥的长度必须是8的倍数,可取24位或32位;(2)加密结果的byte数组转换为字符串,一般采用两种方式:Base64处理或十六进制处理。




