-
-
Save ntccloud/99b036e7937b9414bec8f39f1c0d83f6 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; | |
$msg = substr( $decrypted_msg, 41 ); | |
return $decrypted_msg; | |
} | |
$d = encrypt('this is message', 'secret key'); | |
echo decrypt($d,'secret key'); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment