How to compare encrypted data with crypt

Asked

Viewed 328 times

1

Hello, I’m trying to learn how to encrypt data. I created a code php to save the data in the database mySQL and another to compare user input data with the database.

To encrypt I used the function crypt(). The problem is that when I do the comparison is generated a new encrypted password that does not match the bank, how to solve this? My version of php is 5.3.4.

<?php

     //cadastramento
     $senha = $_POST["senha"];

    //criptografar senha
    $cript_senha =  crypt($senha);

    $sql = "SELECT senha FROM administrador";

    //cadastrar administrador   
    $sql = "INSERT INTO administrador (senha)       
    VALUES ('$cript_senha')";

    if (mysqli_query($conn, $sql)) {

         print "Registrado com sucesso!";

    } else {

        print "Error: " . $sql . "<br>" . mysqli_error($conn);
    }

?>

<?php
    //entrada do usuário 
    $senha = $_POST["senha"];

    $sql = "SELECT  senha FROM administrador";

    //quando faço a comparação não da certo, 
    //pois é gerada uma nova      
    //senha  que   não confere com a do banco

    if ((crypt($senha, $row["senha"])) == $row["senha"]) {

        print "Senhas idênticas";


    } else {

         print "Senhas diferentes ";
    } 

?>
  • 1

    According to the documentation, the second parameter is a salt, and you are passing the password ja from the bank. remove the $row["senha"] if and see if it works.

  • Der a var_dump in the array $rows if he actually has the index senha check in your database if the column size senha has a size large enough to store the encrypted password, recommend leaving the column with a varchar(255). 'Cause the bank can crash truncando (breaking) the value and so the validation does not check.

  • @Diegofelipe the if of it is correct, so is the validation, in the salt would be the encrypted password.

3 answers

2

To make the comparison with the encrypted password you need to have two already encrypted password or encrypt them at runtime, so notice you are comparing an encrypted password with a password without being encrypted which will actually never be equal.

  • I used the first example of this http://php.net/manual/en/function.crypt.php

  • You should use a fixed string combination as the second parameter of the cript function because if you use one that changes it will encrypt the same password differently, which would cause problems in your comparison. Example: &Salt = '12318484' crypt ( string $password [, string $salt ] ) This way the base of the encryption will always be the same, avoiding problems in comparison.

  • @Antonioraichaski in this case the salt should have the value of encrypted data, always used like this and never had problem. His column from MySQL must be set to a small size and ended up truncating the encrypted password.

  • 1

    But salt would be the base that he will use to encrypt the value informed, I imagine it would not be correct to inform the field already encrypted as salt, but if it works...

1

Correct comparison

if ((crypt($senha)) == $row["senha"]) {
    // Senhas iguais
}

I believe that the correct code in the comparison is this, and not crypt($senha, $row["senha"]) as asked in the question, so I think the way I put it works.

1

The error is probably not in the verification, but in the database, the column where the senha should be stored is probably set to a length pequeno thus truncando the generated encryption. I set a small example:

SQL:

CREATE DATABASE IF NOT EXISTS `administrador`;
USE DATABASE `administrador`;

CREATE TABLE IF NOT EXISTS `administrador` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `senha` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1;

Note that the password field is set to up length 255 characters (enough not to truncate more).

Index:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <form method="post" action="php.php?action=register">
            Senha: <input type="text">
            <input type="submit" value="Cadastrar">
        </form>
        <form method="post" action="php.php?action=login">
            Senha: <input type="text">
            <input type="submit" value="Login">
        </form>
    </body>
</html>

php.php: (registration and validation)

$action = $_REQUEST['action'];

//cadastramento
if($action == "register") {
    @$senha = $_POST["senha"];

    //criptografar senha
    $cript_senha =  crypt($senha);

    $sql = "SELECT senha FROM administrador";

    //cadastrar administrador   
    $sql = "INSERT INTO administrador (senha)   VALUES ('$cript_senha')";

    if (mysqli_query($conn, $sql)) {
        //se ocorrer tudo certo volta para o index para ser feito login
        header("location:index.php?info=ok");

    } else {

       print "Error: " . $sql . "<br>" . mysqli_error($conn);
    }
} else if($action == "login") {
    //entrada do usuário 
    @$senha = $_POST["senha"];

    $sql = "SELECT  senha FROM administrador";
    //executa minha sql e pega o resultado em $row
    $query = mysqli_query($conn, $sql);
    $row = mysqli_fetch_assoc($query);

    var_dump($row); //mostra $row

    if ((crypt($senha, $row["senha"])) == $row["senha"]) {
        print "Senhas idênticas"; // agora ele autenticará
    } else {

         print "Senhas diferentes ";
    } 
}

That should solve your problem!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.