Keeping your passwords in a database in a plane format is a very bad idea. So why not to use hashing? Sure you can use hash, end it is totally OK to compare hash against hash. Especially if the password you want to store are not yours. Then this is the way to do it right.

However… what if we build password manager for our own sake, and you want to be able to decrypt the stored Girish to a raw password? In this case, you will need to encrypt the password instead of hashing it.

How to encrypt and decrypt password. Bidirectional hashing?.

There is no such thing as two directional/reversible Hashing. “Reversible hashing” is simply called Encryption.

How to encrypt text in PHP?

We can use openssl_encrypt() function to encrypt text, and later you will use openssl_decrypt() function with same settings and parameters to decrypt this data. In the example below, I store the password in the form of a file with plain text inside (It can be any text string). Just remember, if you change the key after encryption, you will not be able to decrypt the data.

Normally we would run some PDO connection to database, but we want to keep it simple, so we will hardcode all de data in the script below (except encryption secret phase).

app.php code:

<?php

/**
 * Display available ciphering methods
 */
// $ciphers_and_aliases = openssl_get_cipher_methods(true);
// var_dump($ciphers_and_aliases);
 

 /**
 * Encrypt with openssl_encrypt()
 */
// Store a string into the variable which
// need to be Encrypted
$simple_string = "This text will be ecrypted!!!";
 
// Display the original string
echo "Original String: " . $simple_string;
 
// Store the cipher method
$ciphering = "aria128";

// Use OpenSSl Encryption method
$iv_length = openssl_cipher_iv_length($ciphering);
$options = 0;
 
// Non-NULL Initialization Vector for encryption
$encryption_iv = '1234567812345678';
 
// Store the encryption key
// $encryption_key = "Wiktor";
$encryption_key = (string)file_get_contents("./secret.txt");
 
// Use openssl_encrypt() function to encrypt the data
$encryption = openssl_encrypt($simple_string, $ciphering, $encryption_key, $options, $encryption_iv);
 

/**
 * Decrypt
 */

// $ciphering = "camellia-128-cfb";

// Display the encrypted string
echo "Encrypted String: " . $encryption . "\n";
 
// Non-NULL Initialization Vector for decryption
$decryption_iv = '1234567812345678';
 
// Store the decryption key
$decryption_key = (string)file_get_contents("./secret.txt");
 
// Use openssl_decrypt() function to decrypt the data
$decryption=openssl_decrypt($encryption, $ciphering, 
        $decryption_key, $options, $decryption_iv);
 
// Display the decrypted string
echo "Decrypted String: " . $decryption;

Run the script:

cd to file directory and run the fallowing:

php app.php

Output:

Src: https://www.geeksforgeeks.org/how-to-encrypt-and-decrypt-passwords-using-php/

0
Would love your thoughts, please comment.x
()
x