如何解决php加密和解密cookies
我有以下类,我试图用它来加密和解密我的 cookie。我需要将用户 ID 存储在 Keep Me Logged In
功能的 cookie 中,以便用户即使关闭浏览器并稍后返回也保持登录状态。我正在使用的以下功能适用于加密。但是,它不适用于解密。我从 this question 得到了这门课。
$key = 'alabooencryptionkey';
$iv = AES256Encryption::generateIv();
class AES256Encryption {
public const BLOCK_SIZE = 8;
public const IV_LENGTH = 16;
public const CIPHER = 'AES256';
public static function generateIv(bool $allowLessSecure = false): string {
$success = false;
$random = openssl_random_pseudo_bytes(openssl_cipher_iv_length(static::CIPHER));
if(!$success) {
if (function_exists('sodium_randombytes_random16')) {
$random = sodium_randombytes_random16();
}else{
try {
$random = random_bytes(static::IV_LENGTH);
}catch (Exception $e) {
if($allowLessSecure) {
$permitted_chars = implode('',array_merge(
range('A','z'),range(0,9),str_split('~!@#$%&*()-=+{};:"<>,.?/\'')
)
);
$random = '';
for($i = 0; $i < static::IV_LENGTH; $i++) {
$random .= $permitted_chars[mt_rand(0,(static::IV_LENGTH) - 1)];
}
}else{
throw new RuntimeException('Unable to generate initialization vector (IV)');
}
}
}
}
return $random;
}
protected static function getPaddedText(string $plainText): string {
$stringLength = strlen($plainText);
if($stringLength % static::BLOCK_SIZE) {
$plainText = str_pad($plainText,$stringLength + static::BLOCK_SIZE - $stringLength % static::BLOCK_SIZE,"\0");
}
return $plainText;
}
public static function encrypt(string $plainText,string $key,string $iv): string {
$plainText = static::getPaddedText($plainText);
return base64_encode(openssl_encrypt($plainText,static::CIPHER,$key,OPENSSL_RAW_DATA,$iv));
}
public static function decrypt(string $encryptedText,string $iv): string {
return openssl_decrypt(base64_decode($encryptedText),$iv);
}
}
我在这里使用它来加密我的 cookie,它工作正常。
function setLoginCookieSession($user){
global $key,$iv;
$_SESSION['newchatapp'] = $user;
setcookie("newchatapp",AES256Encryption::encrypt($user,$iv),time()+3600*24*365*10,'/');
}
这里用于解密哪个不起作用。它什么都不返回。
function sessionUser(){
global $key,$iv;
// return (isset($_SESSION['newchatapp']))?$_SESSION['newchatapp']:AES256Encryption::decrypt($_COOKIE['newchatapp'],$iv);
return AES256Encryption::decrypt($_COOKIE['newchatapp'],$iv);
}
即使我手动输入尝试解码加密字符串,它仍然没有返回任何内容。
echo AES256Encryption::decrypt('ianXhsXhh6MWAHliZoshEA%3D%3D',$iv);
这意味着解密根本不起作用。我该怎么做才能让它发挥作用?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。