You do not store passwords in the database, instead you store their hash, and use this as a comparison at the time you have to log in.
MD5
and SHA1
are of one-way, you cannot break, but there are tables ready that have a multitude of MD5
and its meanings, as well as SHA1
, I would say that SHA1
is a little safer by being little thing slower.
To make it difficult for a weak password to be exposed if your database is leaked, use some salt.
[salt]+[hash-da-senha]
Salt: Random string generated automatically and used to generate the hash result of your password, is usually saved in the database next to the hash generated.
Example of implementation
// Entrada do usuário
$input = 'minhasenha123';
// Gera o hash da senha do usuário
$hash = password_hash($input, PASSWORD_BCRYPT);
// Hash gerado (cada vez será único)
echo $hash;
// Deve ser armazenado no banco e usado para comparação.
Let’s assume that the above code produced the following result:
$2y$10$OOCtogTSo0egjw1ZUHXndei8h/sZGNQh.iKBn9L2T4VbYvSGFEnP.
Each time it runs is unique, but we saved the hash in the database, and now we will use it to compare the login.
// Entrada do usuário no login
$input = 'minhasenha123';
/**
* Código para pegar a hash do banco correspondente
* ao usuário que tentou fazer login
*
* Aqui para exemplo, vamos usar a string, mas em sua aplicação
* deve-se comparar qual usuário solicitou, se ele existe,
* trazer a hash da senha usuário para uma variável, e compara-la
* com o input do login
*/
$hash = '$2y$10$OOCtogTSo0egjw1ZUHXndei8h/sZGNQh.iKBn9L2T4VbYvSGFEnP.';
// Faz a verificação
if (password_verify($input, $hash))
{
echo 'Usuário logado';
}
else
{
echo 'Senha inválida';
}
I also recommend you use the PASSWORD_BCRYPT
that is slower and more robust (yes, slower, it is essential to purposefully decrease performance when the subject is cryptography, so your system is less vulnerable to brute force attacks).
Note: The function password_hash
is available in 5.5 or higher versions of PHP.
This is the simplest implementation and has enough security.
MD5 and SHA1 are remarkably insecure compared to other methods, I advise to take a look at the bcrypt
– Jeferson Assis
I think my question in this case differs in some aspects from the question marked as possible duplicate. I’m being direct about the encryption, which I can use in another situation. The related question asks about how to make a secure system and this can go beyond encryption.
– Diego Souza
And with this talk of insecure, they’ll end up saying that they’re useless and do not play any important role, I recommend you read this.
– Edilson