How to convert Python encryption to PHP?

5

I would like to know if it is possible to convert this encryption to the PHP language, I need to convert the passwords that were generated to be accepted in my Login system on the site, but I do not know how to do it.

I have a database with passwords generated with this encryption in Python:

Python code:

password = "senha do usuario na DB"    
base64.b64encode(hashlib.sha256(hashlib.sha256(password).hexdigest() + "\xf7\x1a\xa6\xde\x8f\x17v\xa8\x03\x9d2\xb8\xa1V\xb2\xa9>\xddC\x9d\xc5\xdd\xceV\xd3\xb7\xa4\x05J\r\x08\xb0").digest())

PHP Login Code:

<?php
if (isset($_REQUEST['iniciar'])) {
    $usuario = $_REQUEST['usuario'];
    $password = $_REQUEST['senha'];

    $sql = $conexion->query("SELECT * FROM users WHERE Username='$usuario'");

    while ($login = $sql->fetch_assoc()) {
        $usuarioDB = $login['Username'];
        $passwordDB = $login['Password2'];
    }
    if ($usuario == isset($usuarioDB) && password_verify($password, $passwordDB)) {
        $_SESSION['logged'] = "Logged";
        $_SESSION['usuario'] = $usuarioDB;
        $_SESSION['senha'] = $passwordDB;
        header("Location: index.php");
    } elseif ($usuario !== isset($usuarioDB)) {
        echo "<div class='error'><span>Login inválido.</span></div>";
    } elseif (password_verify($password, $passwordDB) === FALSE) {
        echo "<div class='error'><span>Senha inválida.</span></div>";
    }
}
?>

Thanks for any help!

    
asked by anonymous 10.08.2017 / 14:19

1 answer

8

I understand that the portion of your Python code "\xf7\x1a\xa6\xde\x8f\x17v\xa8\x03\x9d2\xb8\xa1V\xb2\xa9>\xddC\x9d\xc5\xdd\xceV\xd3\xb7\xa4\x05J\r\x08\xb0" is a salt.

So, first, it should be stored in PHP.

$salt = "\xf7\x1a\xa6\xde\x8f\x17v\xa8\x03\x9d2\xb8\xa1V\xb2\xa9>\xddC\x9d\xc5\xdd\xceV\xd3\xb7\xa4\x05J\r\x08\xb0";

The second detail is that the password_verify function internally uses encryption generated by the crypt function internally. But as in Python you are using the sha256 hash hash, I think the correct approach would be to use the hash function of PHP with the first argument being sha256 .

I also noticed that in Python the base64 is used to generate the hash. In this case you will need the function in PHP that will do something similar, which is base64_encode .

See:

$hash = hash('sha256', hash('sha256', $password) . $salt));

base64_encode($hash) === $login['Password2']

Note: Perhaps for the sake of interpretation your salt (which appears to be in hexadecimal) should be storing a variable using double quotation marks, since \x is interpreted differently by PHP in such cases.

    
10.08.2017 / 15:19