A client recently asked about setting up small base level encryptions on strings to save in the database, so I looked up a small tutorial using openssl_encrypt/openssl_decrypt
and built this:
<?php
$str = 'Morbi ac risus et risus consectetur rhoncus. Curabitur et libero ut tellus congue faucibus. Curabitur varius odio sed euismod congue. Pellentesque id lacinia erat, ut fringilla leo. Praesent in orci sagittis lorem ultrices fringilla ac vitae ipsum. Nam viverra ut leo vel ullamcorper. Phasellus lobortis quis orci et sagittis. Mauris fringilla eleifend nunc, a lobortis metus ornare quis. Proin a lacinia sem. Vivamus pulvinar cursus ipsum at vehicula.';
$pw = 'opensesame';
$salt = sha1(mt_rand());
$iv = substr(sha1(mt_rand()), 0, 16);
echo "
Password: $pw
Message: $str
Salt: $salt
IV: $iv
";
$encrypted = openssl_encrypt($str, 'AES-128-CBC', "$salt:$pw", null, $iv);
$bundle = "$salt:$iv:$encrypted";
echo " Encrypted bundle = $bundle
";
unset($str, $pw, $salt, $iv, $encrypted);
list($salt, $iv, $encrypted) = explode(':', $bundle);
$pw = 'opensesame';
echo "
Password: $pw
Message: $encrypted
Salt: $salt
IV: $iv
";
$str = openssl_decrypt($encrypted, 'AES-128-CBC', "$salt:$pw", null, $iv);
if ($str === false) {
echo " Invalid password
";
} else{
echo " Message: $str
";
}
list($salt, $iv, $encrypted) = explode(':', $bundle);
$pw = 'bork';
echo "
Password: $pw
Message: $encrypted
Salt: $salt
IV: $iv
";
$str = openssl_decrypt($encrypted, 'AES-128-CBC', "$salt:$pw", null, $iv);
if ($str === false) {
echo " Invalid password
";
} else{
echo " Message: $str
";
}
Initially I was content that it successfully encrypted the string, and later decrypted it accurately. For the sake of being thorough I decided to add a use case where the incorrect password was given instead, and much to my dismay the incorrect password also worked. A bit of tinkering later, I noted that if the encryption key was $pw:$salt
instead of $salt:$pw
, incorrect passwords would fail properly.
But why is that? I looked through the documentation for both functions, and didn't note anything in particular that would cause this. Is this a problem with my code and how I create the salt and iv?