Search code examples
phpmysqlpdopassword-hash

Forgotten Password script with PDO (decrypt needed)


I have maybe a litle stupid ask... I am doing a forgotten password script (to login system of course) but i am stucked. I created a code (it´s working, yeah !) with a special ID, but i can´t decrypt it... Can you please help me ?

Here is my function of creating special ID :

Recovery_Script.php

<?php

include "pdo.php"; if(isset($_POST["submit"]) AND isset($_POST["ForgotPassword"])) {

$email = $_POST["ForgotPassword"];
// Check to see if a user exists with this e-mail
$sql = "SELECT email FROM account WHERE email=:email";
$stmt = $db->prepare($sql);
$stmt->execute(array(":email"=>$email));
$items = $stmt->fetchAll();
$db = null;
 foreach($items as $data){
       if($data["email"] == $email){
        // Create a unique salt. This will never leave PHP unencrypted.
        $salt = "498#2D83B631%3800EBD!801600D*7E3CC13";

        // Create the unique user password reset key
        $password = hash('sha256', $salt.$email);

        // Create a url which we will direct them to reset their password
        $pwrurl = "http://student.sps-prosek.cz/~kocvaja14/Project/SelfMade/templates/script/recovery_password.php?q=".$password;

        // Mail them their key
        $mailbody = "Dobrý den,\n\nJestli tento email nepatří vám, prosím, ignorujte jej. Byla vytvořena žádost o obnovení hesla na webové stránce http://student.sps-prosek.cz/~kocvaja14/SelfMade/\n\nPro obnovení hesla klikněte na odkaz níže. \n\nThanks,\nThe Administration";
        mail($email, "http://student.sps-prosek.cz/~kocvaja14/Project/SelfMade/index.php - Password Reset", $mailbody);
        echo "Your password recovery key has been sent to your e-mail address.";

} else
    echo "No user with that e-mail address exists.";  
      } }?>

And now i need create file, where i will decrypt this ID ($password). But i can´t do it (cuz i have low knowledge about this stuff). Can you help me with it please ? Thank you !


Solution

  • It is not possible to decrypt a sha-hashed value.

    What you will need to do is abandon the idea of a password recovery, but instead construct a password reset system.

    One method of doing this is something like so:

    1. In your user table, add a column for "reset_hash" (a nice long hashed string)
    2. When the user requests a password reset, build a hashed value and store it in their record. Then, in the e-mail, send a link that includes that "reset_hash" as part of the url.
    3. When the user follows the url, check the hash exists in the user table. If so, present a form in which the user can change their password.

    Additional precautions you should consider might including using a NONCE, and validating the NONCE which is one way you can cause the link to expire after X hours (NONCEs are only valid for a period of time).