Skip to content

Instantly share code, notes, and snippets.

@nim4n136
Last active March 11, 2024 21:17
Show Gist options
  • Save nim4n136/7fa38467181130f5a2270c39d495101e to your computer and use it in GitHub Desktop.
Save nim4n136/7fa38467181130f5a2270c39d495101e to your computer and use it in GitHub Desktop.
Encryption & Decryption salt in PHP with OpenSSL
<?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');
@TheCoderRaman
Copy link

Really Useful function

Just remove extra comma ;
From this line

$components = explode( ':', $msg_encrypted_bundle );;

@nim4n136
Copy link
Author

Really Useful function

Just remove extra comma ;
From this line

$components = explode( ':', $msg_encrypted_bundle );;

thanks

@eiusit
Copy link

eiusit commented May 19, 2021

Thanks!
Just a question: why $msg = substr( $decrypted_msg, 41 ); since $msg value is not used anywhere and not returned by decrypt function?

@webeleven-tbarbosa
Copy link

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