Decode hash sha256 encryption, knowing the salt

franvergara66 picture franvergara66 · Sep 7, 2013 · Viewed 38.2k times · Source

I'm making a login system for a web application. To store passwords in the DB, I'm encrypting passwords using sha256 as follows:

$salt ="sometext";
$escapedPW="userpass";
$saltedPW =  $escapedPW . $salt;
$hashedPW = hash('sha256', $saltedPW);
echo "<center>".$hashedPW."</center>";

In the database I am storing the user, the user's password and the salt used to make hash and validate the user's login. Right now I'm doing the functionality to send to the user an email with your password, but when the user receives the email, since is stored in sha256 encrypted password, the user receives a long string and not the password that the user is supposed to know.

My question is there any way that I can send you the actual user password and non the password encryption, ie, there is some way to do the reverse of sha256 if I know the salt?. If not possible, what method of encryption is recommended for you to complete the reverse of the encryption key and send the actual password to the user in an email.

Answer

Henrik Skogmo picture Henrik Skogmo · Sep 7, 2013

As mentioned in the comments of your question, reversing the hash is not really an option.

What you can do however, and this is what everybody else does as well. In your registration code (ex. register.php) which your form post to you can make the PHP script send the password in an email and then encrypt it and store it in the database.

I suppose you have a registration form of some kind, and that form supposedly posts the new users details to another (or the same) php script, doesn't it?

For example if my form said something like <form method="post" action="register.php">

And in register.php I would then have something like

<?php
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']); /*cleartext*/
$email    = mysql_real_escape_string($_POST['email']);

mail($email,"New account","Your username \"$username\" and your password is \"$password\"");

$salt ="sometext";
$escapedPW="userpass";
$saltedPW =  $escapedPW . $salt;
$hashedPW = hash('sha256', $saltedPW);

mysql_query("INSERT INTO users (username, password, email) VALUES ($username, $hashedPW, $email)")

Some rough example code. I hope it helps!