Sometimes, we want to use PHP to encrypt and decrypt passwords.
In this article, we’ll look at how to use PHP to encrypt and decrypt passwords.
How to use PHP to encrypt and decrypt passwords?
To use PHP to encrypt and decrypt passwords, we can base64_encode
and base64_decode
.
For instance, we write
$key = 'password to (en/de)crypt';
$string = ' string to be encrypted ';
$iv = mcrypt_create_iv(
mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC),
MCRYPT_DEV_URANDOM
);
$encrypted = base64_encode(
$iv .
mcrypt_encrypt(
MCRYPT_RIJNDAEL_128,
hash('sha256', $key, true),
$string,
MCRYPT_MODE_CBC,
$iv
)
);
to call base64_encode
with the mcrypt_encrypt
method that hashes the password and then attach it to the initialization vector string $iv
.
The password $string
is in the 3rd argument.
And to do decryption, we call mcrypt_decrypt
by writing
$data = base64_decode($encrypted);
$iv = substr($data, 0, mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC));
$decrypted = rtrim(
mcrypt_decrypt(
MCRYPT_RIJNDAEL_128,
hash('sha256', $key, true),
substr($data, mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC)),
MCRYPT_MODE_CBC,
$iv
),
"\0"
);
to call mcrypt_decrypt
with the hash of the $key
and the encrypted password string without the $iv
that we get with substr($data, mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC))
.
Conclusion
To use PHP to encrypt and decrypt passwords, we can base64_encode
and base64_decode
.