Last active
March 7, 2025 01:02
-
-
Save nim4n136/7fa38467181130f5a2270c39d495101e to your computer and use it in GitHub Desktop.
Encryption & Decryption salt in PHP with OpenSSL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function encrypt($data, $password){ | |
$iv = substr(sha1(mt_rand()), 0, 16); | |
$password = sha1($password); | |
$salt = sha1(mt_rand()); | |
$saltWithPassword = hash('sha256', $password.$salt); | |
$encrypted = openssl_encrypt( | |
"$data", 'aes-256-cbc', "$saltWithPassword", null, $iv | |
); | |
$msg_encrypted_bundle = "$iv:$salt:$encrypted"; | |
return $msg_encrypted_bundle; | |
} | |
function decrypt($msg_encrypted_bundle, $password){ | |
$password = sha1($password); | |
$components = explode( ':', $msg_encrypted_bundle ); | |
$iv = $components[0]; | |
$salt = hash('sha256', $password.$components[1]); | |
$encrypted_msg = $components[2]; | |
$decrypted_msg = openssl_decrypt( | |
$encrypted_msg, 'aes-256-cbc', $salt, null, $iv | |
); | |
if ( $decrypted_msg === false ) | |
return false; | |
return $decrypted_msg; | |
} | |
$d = encrypt('this is message', 'secret key'); | |
echo decrypt($d,'secret key'); | |
Is there any update to use on php ^8.2?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks!
Just a question: why $msg = substr( $decrypted_msg, 41 ); since $msg value is not used anywhere and not returned by decrypt function?