写一个php通用的加密解密字符串的函数给我
以下是一个简单的加密解密字符串的PHP函数:
function encrypt_decrypt($action, $string, $secret_key) { $output = false;
$encrypt_method = "AES-256-CBC";
$secret_iv = 'This is my secret iv';
$key = hash('sha256', $secret_key);
$iv = substr(hash('sha256', $secret_iv), 0, 16);
if ($action == 'encrypt') {
$output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
$output = base64_encode($output);
} else if ($action == 'decrypt') {
$output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
}
return $output;
}
使用方法:
// 加密字符串 $encrypted = encrypt_decrypt('encrypt', 'Hello World', 'my_secret_key'); echo $encrypted;
// 解密字符串 $decrypted = encrypt_decrypt('decrypt', $encrypted, 'my_secret_key'); echo $decrypted;
请注意,这只是一个简单的加密解密函数,可能不适合所有用例。对于更高级的安全需求,您可能需要使用更复杂的加密算法和更多的安全措施。
原文地址: https://www.cveoy.top/t/topic/bIiW 著作权归作者所有。请勿转载和采集!