Sitemap

Secure Text Encryption and Decryption using PHP

4 min readAug 10, 2023

--

Press enter or click to view image in full size
Secure Text with Encryption and decryption
Secure Text with Encryption and decryption

In today’s digital age, data security and privacy have become paramount concerns. Whether you’re handling sensitive user information or confidential messages, encryption is a crucial technique to ensure that your data remains secure and unreadable by unauthorized parties. In this blog post, we’ll explore how to encrypt and decrypt text using PHP, and we’ll provide a step-by-step guide along with code examples.

Understanding Encryption and Decryption:

Encryption is the process of converting plaintext data into ciphertext, making it unreadable without the appropriate decryption key. Decryption, on the other hand, is the process of converting the ciphertext back into its original plaintext form using the decryption key. The use of encryption ensures that even if an attacker gains access to the encrypted data, they won’t be able to understand it without the decryption key.

Prerequisites:

Before we dive into the code, make sure you have a basic understanding of PHP and web development. Also, ensure that you have a web server with PHP installed to execute the code.

The Code:

HTML Structure: The HTML portion of the code provides a user-friendly interface with two forms: one for encryption and one for decryption. Users can enter the text they want to encrypt or decrypt, along with the appropriate encryption or decryption key. Upon submission, the PHP code checks for the form that was submitted and calls the corresponding function to perform the encryption or decryption. The results are then displayed on the page. The HTML structure defines two forms: one for encrypting text and another for decrypting text. Each form contains input fields for the necessary data.

<!DOCTYPE html>
<html>
<head>
<title>Encryption & Decryption</title>
</head>
<body>
<h2>Encryption & Decryption Example</h2>
<!--Encrypt Form-->
<form method="post" action="action.php">
<label for="plaintext">Enter text to encrypt:</label><br>
<textarea name="plaintext" id="plaintext" rows="4" cols="40"></textarea>
<br>
<br>
<label for="encryptionkey">Enter the encryption key:</label>
<br>
<input type="password" name="encryptionkey" id="encryptionkey">
<br>
<br>
<input type="submit" name="encrypt" value="Encrypt">
</form>

<!--Decrypt Form-->
<form method="post" action="action.php">
<label for="encryptedText">Enter text to decrypt:</label>
<br>
<textarea name="encryptedText" id="encryptedText" rows="4" cols="40"></textarea>
<br>
<br>
<label for="decryptionKey">Enter the decryption key:</label>
<br>
<input type="password" name="decryptionKey" id="decryptionKey">
<br>
<br>
<input type="submit" name="decrypt" value="Decrypt">
</form>
</body>
</html>

Encryption Function: The encryptText function takes plaintext and an encryption key as inputs. It generates a random initialization vector (IV) using the openssl_random_pseudo_bytes function. The plaintext is then encrypted using the AES-256-CBC algorithm and the provided key. The IV is prepended to the encrypted text, and the combined data is base64-encoded to ensure safe transmission.

function encryptText($text, $key) {
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
$encrypted = openssl_encrypt($text, 'aes-256-cbc', $key, 0, $iv);
return base64_encode($iv . $encrypted);
}

Decryption Function: The decryptText function takes encrypted text and a decryption key as inputs. It decodes the base64-encoded input and separates the IV from the encrypted data. Using the IV and decryption key, it then decrypts the encrypted data back to the original plaintext.

function decryptText($encryptedText, $key) {
$data = base64_decode($encryptedText);
$ivSize = openssl_cipher_iv_length('aes-256-cbc');
$iv = substr($data, 0, $ivSize);
$encrypted = substr($data, $ivSize);
return openssl_decrypt($encrypted, 'aes-256-cbc', $key, 0, $iv);
}

Form Processing: The PHP code checks the request method (POST) to determine whether the user submitted the form. If the “Encrypt” button is clicked, the plaintext and encryption key are used to encrypt the text, and the result is displayed. If the “Decrypt” button is clicked, the encrypted text and decryption key are used to decrypt the text, and the result is displayed.

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['encrypt'])) {
$plaintext = $_POST['plaintext'];
$encryptionKey = $_POST['encryptionkey'];
$encryptedText = encryptText($plaintext, $encryptionKey);
echo "<h3>Encrypted Text:</h3>";
echo "<p>$encryptedText</p>";
} else if (isset($_POST['decrypt'])) {
$encryptedText = $_POST['encryptedText'];
$decryptionKey = $_POST['decryptionKey'];
$decryptedText = decryptText($encryptedText, $decryptionKey);
echo "<h3>Decrypted Text:</h3>";
echo "<p>$decryptedText</p>";
}
}

Full PHP Code:

<?php
function encryptText($text, $key) {
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
$encrypted = openssl_encrypt($text, 'aes-256-cbc', $key, 0, $iv);
return base64_encode($iv . $encrypted);
}

function decryptText($encryptedText, $key) {
$data = base64_decode($encryptedText);
$ivSize = openssl_cipher_iv_length('aes-256-cbc');
$iv = substr($data, 0, $ivSize);
$encrypted = substr($data, $ivSize);
return openssl_decrypt($encrypted, 'aes-256-cbc', $key, 0, $iv);
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['encrypt'])) {
$plaintext = $_POST['plaintext'];
$encryptionKey = $_POST['encryptionkey'];
$encryptedText = encryptText($plaintext, $encryptionKey);
echo "<h3>Encrypted Text:</h3>";
echo "<p>$encryptedText</p>";
} else if (isset($_POST['decrypt'])) {
$encryptedText = $_POST['encryptedText'];
$decryptionKey = $_POST['decryptionKey'];
$decryptedText = decryptText($encryptedText, $decryptionKey);
echo "<h3>Decrypted Text:</h3>";
echo "<p>$decryptedText</p>";
}
}
?>

Security Considerations:

While this example provides a basic understanding of text encryption and decryption using PHP, it’s important to note that security is a complex topic. Some considerations include:

  1. Key Management: Safeguard your encryption and decryption keys. In a real-world scenario, using user-provided keys might not be the most secure approach.
  2. Randomness: Use proper random number generators to generate IVs and keys to prevent predictable patterns.
  3. Authentication: Encryption alone does not ensure the authenticity of the sender or the integrity of the data. Consider combining encryption with digital signatures.
  4. Algorithm and Mode: Choose appropriate encryption algorithms and modes based on security requirements.
  5. Secure Communication: Ensure that encrypted data is transmitted over secure channels (e.g., HTTPS).

Conclusion:

Implementing text encryption and decryption using PHP can provide an extra layer of security for sensitive information. While this example provides a basic introduction, real-world security practices involve more complexity and considerations. Always stay updated with the latest security practices and technologies to ensure the protection of your data in an increasingly interconnected digital world.

Get Everyday Programmer’s stories in your inbox

Join Medium for free to get updates from this writer.

You can get the working full source code from GitHub from here: https://github.com/Everyday-Programmer/Encryption-Decryption-PHP

YouTube tutorial to encrypt and decrypt text using php

Make sure to subscribe, so that you won’t miss any contents.

Happy Coding :)

--

--

Everyday Programmer
Everyday Programmer

Written by Everyday Programmer

Join me on my coding journey as I explore the realms of algorithms, data structures, and software magic. Let's conquer the code together! 🚀