首页 > 解决方案 > 结合“openssl_encrypt”和“hash_hmac”来加密数据的最安全方法是什么?

问题描述

我想通过使用安全胡椒加密散列密码来为我的散列密码(使用带有 argon2i 的 password_hash 函数)增加一层额外的安全性,该密码被安全地保存在我的 wordpress 网站公共区域之外的目录中。

我做了很多研究并想出了以下 php 代码。但我不是专业程序员,所以我只是问自己,如果这是正确的方法,我是如何使用“openssl_encrypt()”和“hash_hmac()”这两个函数的。

如果能从你们那里得到一些专业的反馈,那就太好了。

到目前为止,这是我的代码:

// Encryption Function
function secured_encrypt($data) {
        $first_key  = base64_decode(FIRSTKEY);
        $second_key = base64_decode(SECONDKEY);
        $method     = "aes-256-cbc";   
        $iv_length  = openssl_cipher_iv_length($method);
        $iv         = openssl_random_pseudo_bytes($iv_length);
               
        $first_encrypted    = openssl_encrypt($data,$method,$first_key, OPENSSL_RAW_DATA ,$iv);   
        $second_encrypted   = hash_hmac('sha3-512', $first_encrypted, $second_key, TRUE);
                   
        $output = base64_encode($iv.$second_encrypted.$first_encrypted);   
        return $output;
}
 
function secured_decrypt($input) {
        $first_key  = base64_decode(FIRSTKEY);
        $second_key = base64_decode(SECONDKEY);           
        $mix        = base64_decode($input);
               
        $method     = "aes-256-cbc";   
        $iv_length  = openssl_cipher_iv_length($method);
                   
        $iv                 = substr($mix,0,$iv_length);
        $second_encrypted   = substr($mix,$iv_length,64);
        $first_encrypted    = substr($mix,$iv_length+64);
                   
        $data   = openssl_decrypt($first_encrypted,$method,$first_key,OPENSSL_RAW_DATA,$iv);
        $second_encrypted_new   = hash_hmac('sha3-512', $first_encrypted, $second_key, TRUE);
           
        if (hash_equals($second_encrypted,$second_encrypted_new)) return $data;
          
        return false;
}

标签: phpsecurityencryptionhashphp-openssl

解决方案


推荐阅读