How to encrypt data in PHP?

by mallory_cormier , in category: PHP Security , a year ago

How to encrypt data in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by giovanny.lueilwitz , a year ago

@mallory_cormier 

Encrypting data in PHP can be done using various encryption algorithms such as AES, Blowfish, and RSA. Here's an example of how to encrypt data using the AES encryption algorithm in PHP:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
$data = "My secret message";
$key = "My secret key"; // This key should be kept secret

// Encrypt the data using AES-256-CBC algorithm
$encrypted = openssl_encrypt($data, 'aes-256-cbc', $key, OPENSSL_RAW_DATA);

// Convert the encrypted data to base64 encoding for safe transport
$encrypted = base64_encode($encrypted);

echo $encrypted; // Output: JHTQvN57ZK9JBEuI+DHzVQ==


In this example, we first define the data that we want to encrypt and the secret key that we will use to encrypt it. We then use the openssl_encrypt function to encrypt the data using the AES-256-CBC encryption algorithm, which is a symmetric encryption algorithm that uses the same key for both encryption and decryption. Finally, we convert the encrypted data to base64 encoding for safe transport.


To decrypt the encrypted data, we can use the openssl_decrypt function:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
$encrypted = "JHTQvN57ZK9JBEuI+DHzVQ==";
$key = "My secret key"; // This key should be kept secret

// Convert the encrypted data from base64 encoding
$encrypted = base64_decode($encrypted);

// Decrypt the data using AES-256-CBC algorithm
$decrypted = openssl_decrypt($encrypted, 'aes-256-cbc', $key, OPENSSL_RAW_DATA);

echo $decrypted; // Output: My secret message


In this example, we first convert the encrypted data from base64 encoding and then use the openssl_decrypt function to decrypt the data using the same key and algorithm that we used for encryption. The output of the decryption process is the original data that we encrypted.