class Crypt
{
protected static $key = "123456"; // key
protected static $cipher = "AES-128-CBC"; // 密码学方式
protected static $options = 1; // 0 => OPENSSL_ZERO_PADDING , 1 => "OPENSSL_RAW_DATA"
protected static $hmacAgo = "sha256"; // hash加密方式 sha256,md5等
protected static $hmacLen = 2 ; // 记录加密方式加密后长度
/****
* 加密
* @param $data
* @return string
*/
public static function encrypt($data){
if (!is_string($data)){
return false;
}
$ivLen = openssl_cipher_iv_length(self::$cipher);
$iv = openssl_random_pseudo_bytes($ivLen);
$dataRaw = openssl_encrypt($data,self::$cipher,self::$key,self::$options,$iv);
$hmac = hash_hmac(self::$hmacAgo,$dataRaw,self::$key,true);
return base64_encode($iv.strlen($hmac).$hmac.$dataRaw);
}
/****
* 解密
* @param $data
* @return false|string
*/
public static function decrypt($data){
if (!is_string($data)){
return false;
}
$ivLen = openssl_cipher_iv_length(self::$cipher);
$c = base64_decode($data);
$iv = substr($c,0,$ivLen);
$hash2Len = substr($c,$ivLen,self::$hmacLen);
$hmac = substr($c,$ivLen+self::$hmacLen,$hash2Len);
$dataRaw = substr($c,$ivLen+self::$hmacLen+$hash2Len);
$data = openssl_decrypt($dataRaw,self::$cipher,self::$key,self::$options,$iv);
$calCmac = hash_hmac(self::$hmacAgo,$dataRaw,self::$key,true);
if (hash_equals($hmac,$calCmac)){
return $data;
}
return false;
}
}