• How to Encrypt Password in PHP using Various Methods?

    Simple ways to encrypt password in PHP are md5(), sha() and crypt(). We can protect password using it.

    Method 1: Password encryption using md5()

    Below is an example:

    1
    2
    3
    4
    5
    6
    
    <?php
    $var = "password";
    $enc = md5($var);
    echo "Original Text - $var";
    echo "Encrypted Text - $enc";
    ?>

    Output:
    Original Text – password
    Encrypted Text – 5f4dcc3b5aa765d61d8327deb882cf99

    For password, add encrypted password into the database.
    And when login is requested, encrypt user’s entered password and compare it with the one in user’s database.

    Method 2: Password encryption using SHA1()

    Below is an example:

    1
    2
    3
    4
    5
    6
    
    <?php
    $var = "password";
    $enc = sha1($var);
    echo "Original Text - $var";
    echo "Encrypted Text - $enc";
    ?>

    Output:
    Original Text – password
    Encrypted Text – 5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8

    For password, add encrypted password into the database.
    And when login is requested, encrypt user’s entered password and compare it with the one in user’s database.

    Method 3: Password encryption using crypt()

    Below is an example:

    1
    2
    3
    4
    5
    6
    
    <?php
    $var = "This is test";
    $enc = crypt($var); //salt be automatically generated
    echo "Original Text - $var";
    echo "Encrypted Text - $enc";
    ?>

    Output:
    Original Text – This is test
    Encrypted Text – $1$5K5DEarv$JVOClfGDlGEZQ4IKWqQ8v1

    For password, add encrypted password into the database.
    And when login is requested, use encrypt() as below to validate the password.

    1
    2
    3
    4
    
    <?php
    if (crypt($input, $password) == $password) {
    echo "Password verified!"; }
    ?>

    where $input in user posted password and $password is the encrypted one in database.

Comments on this post

Leave a Reply

  • Security Code :


    nine × 8 =