Encrypt password and log in PHP and PDO

1

Login.php file

    <?php

    session_start();

    require_once '../includes/config.php';

    if(isset($_REQUEST["post_back"])){

    $tb = $conn->prepare("select nm_usuario, imgPerfil, nome from usuario where nm_usuario=:usuario and senha_usuario=:senha");
    $tb->bindParam(":usuario", $_POST["usuario"], PDO::PARAM_STR);
    $tb->bindParam(":senha", $_POST["senha"], PDO::PARAM_STR);
    $tb->execute();
    $l = $tb->fetch(PDO::FETCH_ASSOC);
    $tb = null;
    if(!empty($l)){

    $_SESSION["usuario"] = $l["nm_usuario"]; // Pegar o Usuario logado
    $_SESSION["imgPerfil"] = $l["imgPerfil"]; // Pegar a imagem do perfil
    $_SESSION["nome"] = $l["nome"];           // Pegar o nome do Usuario logado
    header("Location: ../inicial.php");

    }else{

    echo("<script language = 'javascript'> alert('Usuario ou senha incorretos!'); </script>");
    echo("<script language = 'javascript'> location.href = '../index.php'; </script>");

    }

    }
    ?>

Below the file verify.php

    <?php
    session_start();
    if(!isset($_SESSION["usuario"])){
    header("Location: index.php");
    exit;
    }
    ?>

Below the file exit.php

    <?php
    session_start();

    unset($_SESSION["usuario"]);
    unset($_SESSION["imgPerfil"]);
    unset($_SESSION["nome"]);
    session_destroy();

    header("Location: ../index.php");
    ?>

And below the index.php file where you will be logged in:

    <?php
    session_start();
    if(isset($_SESSION["usuario"])){
    header("Location: inicial.php");
    exit;
    }
    ?>

    <html lang="pt_br">
    <head>
    <meta charset="utf-8" />
    <title>Painel de Controle - Portal WVD</title>
    <link rel="stylesheet" type="text/css" href="css/default.css" media="screen" />
    <script type="text/javascript" src="jquery-1.9.1.js"></script>
        </head>

        <body>

        <main id="login">
        <form id="form1" name="form1" method="post" action="acoes/login.php">
            <table>
        <tbody>
            <tr>
                <td colspan="2"><h1>Painel de Controle</h1></td>
            </tr>
        <tr>
            <td>Usuario:</td>
            <td><input type="text" name="usuario" id="user-name" /></td>
        </tr>

        <tr>
            <td>Senha:</td>
            <td><input type="password" name="senha" id="user-pass" /></td>
        </tr>

        <tr>
            v<td colspan="2"><input type="submit" name="post_back" id="user-login"                value="Iniciar Sessão" /></td>
        </tr>
        </tbody>
            </table>
    </form>

        </main>

</body>
    </html>

I would like to know if this code is correct, if it has to simplify and I would like to encrypt the password but I still have no experience in which encryption to use.

    
asked by anonymous 28.12.2014 / 04:27

1 answer

2

PHP already comes with some functions that can help you to encrypt and decrypt. See the documentation: MD5 and Crypt

However, it is always good to have your own encryption algorithm. Ex:

<?php
class Hash {
private $hasBlowfish;
public function __construct() {
    self::$hasBlowfish = ( CRYPT_BLOWFISH === 1 ) ? TRUE : FALSE;
}
/**
 * Gera um 'salt' único de 22 chars para encriptar password
 * com o algoritmo blowfish.
 *
 * @return String - A unique salt string.
 */
public static function uniqueSalt() {
    return substr( sha1( mt_rand() ), 0, 22 );
}
/**
 * Cria um hash a partir de uma string/password.
 *
 * O hash é gerado com o algortitmo blowfish com um
 * custo 10.
 *
 * @return String - A blowfish, cost-10, hashed password.
 */
public static function hashPassword( $pass ) {
    // if ( ! self::$hasBlowfish ) {
    //     die( 'O servidor não suporta encriptação blowfish...' );
    // }
    return crypt( $pass, '$2a$10$' . self::uniqueSalt() );
}
/**
 * Verifica se um plain password é igual ao password
 * já hasheado. O password já hasheado vem do DB, por exemplo.
 *
 * @return Boolean TRUE if the passwords are the same, FALSE otherwise.
 */
public static function checkPasswords( $DbHashedPassword, $plainPassword ) {
    // Na verdade, nem precisa explicitamente pegar os primeiros 29 chars,
    // já que crypt() automaticamente descarta caracteres excedentes.
    $salt = substr( $DbHashedPassword, 0, 29 );
    $newHash = crypt( $plainPassword, $salt );
    return ( $DbHashedPassword == $newHash );
}
}
    
28.12.2014 / 12:59