note 126546 added to function.openssl-encrypt
| From: | desmatic at gmail dot com | Date: | Sat, 30 Oct 2021 12:39:19 +0000 |
| Subject: | note 126546 added to function.openssl-encrypt | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-217126@lists.php.net to get a copy of this message | ||
Upgraded php and needed something to replace insecure legacy mcrypt libs, but still supported
classic user, password interface.
<?php
function encrypt($plaintext, $key, $cipher = "aes-256-gcm") {
if (!in_array($cipher, openssl_get_cipher_methods())) {
return false;
}
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($cipher));
$tag = null;
$ciphertext = openssl_encrypt(
gzcompress($plaintext),
$cipher,
base64_decode($key),
$options=0,
$iv,
$tag,
);
return json_encode(
array(
"ciphertext" => base64_encode($ciphertext),
"cipher" => $cipher,
"iv" => base64_encode($iv),
"tag" => base64_encode($tag),
)
);
}
function decrypt($cipherjson, $key) {
try {
$json = json_decode($cipherjson, true, 2, JSON_THROW_ON_ERROR);
} catch (Exception $e) {
return false;
}
return gzuncompress(
openssl_decrypt(
base64_decode($json['ciphertext']),
$json['cipher'],
base64_decode($key),
$options=0,
base64_decode($json['iv']),
base64_decode($json['tag'])
)
);
}
$secret = "MySecRet@123";
$cipherjson = encrypt("Hello world!\n", $secret);
echo decrypt($cipherjson, $secret);
?>
----
Server IP: 45.112.84.4
Probable Submitter: 45.112.85.242 (proxied: 86.191.191.147)
----
Manual Page -- https://php.net/manual/en/function.openssl-encrypt.php
Edit -- https://main.php.net/note/edit/126546
Del: integrated -- https://main.php.net/note/delete/126546/integrated
Del: useless -- https://main.php.net/note/delete/126546/useless
Del: bad code -- https://main.php.net/note/delete/126546/bad+code
Del: spam -- https://main.php.net/note/delete/126546/spam
Del: non-english -- https://main.php.net/note/delete/126546/non-english
Del: in docs -- https://main.php.net/note/delete/126546/in+docs
Del: other reasons-- https://main.php.net/note/delete/126546
Reject -- https://main.php.net/note/reject/126546
Search -- https://main.php.net/manage/user-notes.php