随笔 - 20  文章 - 0  评论 - 0  阅读 - 5714

敏感数据简单加密

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;
    }
}

  

posted on 2021-12-20 20:11  此间你我皆无  阅读(44)  评论(0)    收藏  举报
< 2025年6月 >
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 1 2 3 4 5
6 7 8 9 10 11 12

点击右上角即可分享
微信分享提示