敏感数据简单加密
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | 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; } } |
【推荐】博客园的心动:当一群程序员决定开源共建一个真诚相亲平台
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】Flutter适配HarmonyOS 5知识地图,实战解析+高频避坑指南
【推荐】凌霞软件回馈社区,携手博客园推出1Panel与Halo联合终身会员
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步