Search code examples
phpencryptionpasswordsmcrypt

Decrypting passwords that are stored on server with mcrypt


So I have a table that has encrypted usernames and passwords under varbinary using MCRYPT_RIJNDAEL_128 encryption. I can store encrypted details fine, but I have problems decrypting them. I'm storing the username, password and the IV when the user registers.

$query = "INSERT INTO users ( username, password ) VALUES ( :user, :pass) ";

$encrypt_user = $_POST['username'];
$encrypt_pass = $_POST['password'];

$encrypted_user = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $secret_key, $encrypt_user, MCRYPT_MODE_CBC, $iv);
$encrypted_pass = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $secret_key, $encrypt_pass, MCRYPT_MODE_CBC, $iv);
$encrypted_cardnumber = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $secret_key, 

$query_params = array(
    ':user' => $encrypted_user,
    ':pass' => $encrypted_pass,
);

try {
    $stmt   = $db->prepare($query);
    $result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
    $response["success"] = 0;
}

This stores all fine, the question is when I want to decrypt. How can I fetch the IV for the user that logged in? I have tried setting the iv to a session variable when the user registers but I know that only works when a user first registers and then logs in.

$query = "SELECT id, username FROM users WHERE username = :username";

$username = $_POST['username'];
$password = $_POST['password'];
//encrypting the username and password to compare to the ones stored in the databaase
$encrypted_username = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $secret_key, $username, MCRYPT_MODE_CBC, $iv);
$encrypted_password = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $secret_key, $password, MCRYPT_MODE_CBC, $iv);

Solution

  • just don't encrypt the username, as this is no sensitive information. But you should change the method from encrypting to hashing. Because with the IV and the secret_key it's possible to decrypt the password.