How to Encrypt and Decrypt Data in PHP

PHP offers both one-way and two-way encryption methods for securing data. For passwords, password_hash() and password_verify() provide secure, irreversible hashing ideal for authentication. For reversible encryption, openssl_encrypt() and openssl_decrypt() can be used with symmetric keys. Always use strong keys and initialization vectors (IV) when encrypting sensitive information. Choose the method based on whether the data needs to be decrypted later or not.

1. Password Hashing (One-Way Encryption – Recommended)

Use this method when storing user passwords in a database. You can’t decrypt this — it’s one-way only, which is safer.

Hashing the password:

Inside register.php:


<?php
$password = "MySecret123";
$hashed = password_hash($password, PASSWORD_DEFAULT);
echo $hashed;
?>

Verifying the password:

login_process.php


<?php
$enteredPassword = "MySecret123";

if (password_verify($enteredPassword, $hashed)) {
    echo "Password matched!";
} else {
    echo "Invalid password.";
}
?>

Note: password_hash() automatically handles salting and uses strong algorithms (like bcrypt).

2. Two-Way Encryption and Decryption (Not for passwords)

Use this only when you need to decrypt the data later, like for tokens or messages. For passwords, use one-way hashing above.

Encrypt:

encrypt.php


<?php
$key = "secretkey1234567"; // 16 characters for AES-128
$plaintext = "MySecret123";

$iv = openssl_random_pseudo_bytes(16);
$encrypted = openssl_encrypt($plaintext, 'AES-128-CBC', $key, 0, $iv);
$encryptedData = base64_encode($iv . $encrypted);

echo $encryptedData;
?>

Decrypt:

decrypt.php


<?php
$encryptedData = base64_decode($encryptedData);
$iv = substr($encryptedData, 0, 16);
$encrypted = substr($encryptedData, 16);

$decrypted = openssl_decrypt($encrypted, 'AES-128-CBC', $key, 0, $iv);
echo $decrypted;
?>

Summary:

Purpose Method Reversible Use Case
Password protection password_hash() ❌ No Login systems ✅ Recommended
Data encryption openssl_encrypt() ✅ Yes Tokens, personal data (not passwords)