栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何加密和解密PHP字符串?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何加密和解密PHP字符串?

更新

PHP 7就绪版本。它使用PHP
OpenSSL库中的openssl_encrypt函数。

class Openssl_EncryptDecrypt {    function encrypt ($pure_string, $encryption_key) {        $cipher     = 'AES-256-CBC';        $options    = OPENSSL_RAW_DATA;        $hash_algo  = 'sha256';        $sha2len    = 32;        $ivlen = openssl_cipher_iv_length($cipher);        $iv = openssl_random_pseudo_bytes($ivlen);        $ciphertext_raw = openssl_encrypt($pure_string, $cipher, $encryption_key, $options, $iv);        $hmac = hash_hmac($hash_algo, $ciphertext_raw, $encryption_key, true);        return $iv.$hmac.$ciphertext_raw;    }    function decrypt ($encrypted_string, $encryption_key) {        $cipher     = 'AES-256-CBC';        $options    = OPENSSL_RAW_DATA;        $hash_algo  = 'sha256';        $sha2len    = 32;        $ivlen = openssl_cipher_iv_length($cipher);        $iv = substr($encrypted_string, 0, $ivlen);        $hmac = substr($encrypted_string, $ivlen, $sha2len);        $ciphertext_raw = substr($encrypted_string, $ivlen+$sha2len);        $original_plaintext = openssl_decrypt($ciphertext_raw, $cipher, $encryption_key, $options, $iv);        $calcmac = hash_hmac($hash_algo, $ciphertext_raw, $encryption_key, true);        if(function_exists('hash_equals')) { if (hash_equals($hmac, $calcmac)) return $original_plaintext;        } else { if ($this->hash_equals_custom($hmac, $calcmac)) return $original_plaintext;        }    }        function hash_equals_custom($knownString, $userString) {        if (function_exists('mb_strlen')) { $kLen = mb_strlen($knownString, '8bit'); $uLen = mb_strlen($userString, '8bit');        } else { $kLen = strlen($knownString); $uLen = strlen($userString);        }        if ($kLen !== $uLen) { return false;        }        $result = 0;        for ($i = 0; $i < $kLen; $i++) { $result |= (ord($knownString[$i]) ^ ord($userString[$i]));        }        return 0 === $result;    }}define('ENCRYPTION_KEY', '__^%&Q@$&*!@#$%^&*^__');$string = "This is the original string!";$OpensslEncryption = new Openssl_EncryptDecrypt;$encrypted = $OpensslEncryption->encrypt($string, ENCRYPTION_KEY);$decrypted = $OpensslEncryption->decrypt($encrypted, ENCRYPTION_KEY);


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/421599.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号