在网站加密上,前端一般用
实现常用的加密,md5,hash,AES,des,Base64 等等;
然鹅,php端 常用的是 openssl_decrypt
让我们来看看代码
class SecurityHelper {
public static function base64UrlEncode($input)
{
return strtr(base64_encode($input), '+/', '-_');
}
/**
*
* @param string $input encoded string.
* @return string decoded string.
* @since 2.0.12
*/
public static function base64UrlDecode($input)
{
return base64_decode(strtr($input, '-_', '+/'));
}
/**
* 采用aes-128-cbc 加密字符串
*
* @param string $plaintext 待加密的明文
*/
public static function encode($plaintext)
{
try{
$secret = 'yousecrect=16bytes';
$cipher = 'aes-128-cbc';
$keySize = 16;
$iv = \Yii::$app->getSecurity()->generateRandomKey($keySize);
$ciphertext = openssl_encrypt($plaintext, $cipher, $secret, 0, $iv);
return self::base64UrlEncode( $iv.$ciphertext );
}catch(\Exception $e){
return $plaintext;
}
}
/**
* encode 函数的逆算法,解密
* @param string $string
*/
public static function decode_by_key($string)
{
try{
$blockSize = 16;
$cipher = 'aes-128-cbc';
$orign = self::base64UrlDecode($string);
$secret = 'yousecrect=16bytes';
$iv = StringHelper::byteSubstr($orign, 0, $blockSize);
$ciphertext = StringHelper::byteSubstr($orign, $blockSize );
$plantext = openssl_decrypt($ciphertext, $cipher, $secret, 0, $iv);
if($plantext)
return $plantext;
else
return $string;
}catch(\Exception $e){
return $string;
}
}
/**
*
* @param array $params
* @return string
*/
public static function array_encode ($params = [])
{
foreach($params as $key=> $val){
if(!empty($val))
$params[$key] = self::encode($val );
}
return json_encode($params) ;
}
}
好了本文内容全部结束,感谢你的阅读,希望能帮助到您!