php 字符串加密与解密,如何加密和解密PHP字符串?

小编典典

更新

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;

}

}

/**

* (Optional)

* hash_equals() function polyfilling.

* PHP 5.6+ timing attack safe comparison

*/

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

2020-05-26

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值