Skip to content
David Kittell
David Kittell

Application & System: Development / Integration / Orchestration

  • Services
    • Application Development
    • Online Application Integration
  • Code
  • Online Tools
  • Tech Support
David Kittell

Application & System: Development / Integration / Orchestration

PHP – OpenSSL AES Encryption

Posted on October 26, 2015 By David Kittell

This is currently setup as a three file setup, I can not remember where I originally found the code so I can not take full credit for this post.

I use the code below to send a username and date\time to another page. If the date\time is within 2 minutes display decrypted information, but if it has been more than 2 minutes display an error message.

<?PHP
define('AES_METHOD', 'AES-256-CBC');
 
class AES256 
{
    public function Encrypt($password, $plainText)
    {
        if(empty($password) || empty($plainText))
        {
            return FALSE;
        }
 
	//generate a random salt
	$Salt = openssl_random_pseudo_bytes(8);
	if($Salt === FALSE){
            return FALSE;
        }
 
	//generate a random initialization vector
	$IV = openssl_random_pseudo_bytes(
                  openssl_cipher_iv_length(
			AES_METHOD));
        if($IV === FALSE){
            return FALSE;
        }
 
	//generate aes key
	$pwd = substr(hash('sha256', $password), 0, 32);
	$Key = openssl_pbkdf2($pwd, $Salt, 32, 5);
	if($Key === FALSE){
            return FALSE;
        }
 
	//encrypt message
        $cipherText = openssl_encrypt($plainText, 
			AES_METHOD, $Key, true, $IV);
 
	//check if encryption failed
        if($cipherText === FALSE){
            return FALSE;
        }
 
	//create something safer than the following code
	//this is just a demonstration
    $IV64 = base64_encode($IV);
	$Salt64 = base64_encode($Salt);
	$Cipher64 = base64_encode($cipherText);
 
	if($IV64 === FALSE || $Salt64 === FALSE || $Cipher64 === FALSE)
	{
	    return FALSE;
	}
 
        return base64_encode($IV64.'^^'.$Cipher64.'**'.$Salt64);
    }
 
    public function Decrypt($password, $cipherText)
    {
        if(empty($password) || empty($cipherText))
        {
            return FALSE;
        }
 
        $decoded = base64_decode($cipherText);
        if($decoded === FALSE){
            return FALSE;
        }
 
	//locate iv value
	$IV = base64_decode(substr($decoded, 0, 
			strpos($decoded, '^^')));
        if($IV === FALSE){
            return FALSE;
        }
 
	//locate salt value
	$encodedSalt = substr($decoded, 
	    strpos($decoded, '**') + 2, strlen($decoded));
	$Salt = base64_decode($encodedSalt);
        if($Salt === FALSE){
            return FALSE;
        }
 
        //locate cipher text
	$ciphertext = base64_decode(substr($decoded, 
		strpos($decoded, '^^') + 2, 
		-(strlen($encodedSalt)+2)));
        if($ciphertext === FALSE){
            return FALSE;
        }
 
	//generate aes key
	$pwd = substr(hash('sha256', $password), 0, 32);
	$Key = openssl_pbkdf2($pwd, $Salt, 32, 5);
	if($Key === FALSE){
            return FALSE;
        }
 
        return openssl_decrypt($ciphertext, AES_METHOD, $Key, true, $IV);
    }
}
?>

Using the code on OpenSSL Generate Salt, Key and IV we create the password. Make sure in your testing that you change the password and decide what you want to put in the encryption.

<?PHP
require('Function.php');

// Set timezone
date_default_timezone_set("UTC");

define('PASSWORD', '9970197D67354DB93FEDBC8D331EFC3F6B441CD0A2CDB70810971531C23791E9');
// Create a new password (UNIX terminal):  openssl enc -aes-256-cbc -k MySuperSecretPassPhrase -P -md sha1
 
$encryptor = new AES256();
 
$cipher = $encryptor->Encrypt(PASSWORD, 'MyUserName|' . date("Y-m-d H:i:s"));
if($cipher)
	{
		$decrypted = $encryptor->Decrypt(PASSWORD, $cipher);
		
		echo 'Encrypted: '.$cipher.'<br><br>';
		echo 'Decrypted: '.$decrypted.'<br><br>';

		$saDecrypted = explode("|", $decrypted);

		echo 'Username: ' . $saDecrypted[0] . '<br>';
		echo 'Date Time Decrypted: ' . $saDecrypted[1] . '<br>';

		echo 'Current Date Time: ' . date("Y-m-d H:i:s") . '<br>';

		echo '<a href="Process_Sent_Token.php?token='.$cipher.'">Send To Token</a>';
	}
?>

Make sure the password in the encryption is the same as the password in the decryption.

<?PHP
require('Function.php');

// Set timezone
date_default_timezone_set("UTC");

if ((isset($_GET['token'])) && ('' != trim($_GET['token'])))
	{
		define('PASSWORD', '9970197D67354DB93FEDBC8D331EFC3F6B441CD0A2CDB70810971531C23791E9');
		// Create a new password (UNIX terminal):  openssl enc -aes-256-cbc -k MySuperSecretPassPhrase -P -md sha1
 
		$encryptor = new AES256();
		
		$decrypted = $encryptor->Decrypt(PASSWORD, $_GET['token']);
		$saDecrypted = explode("|", $decrypted);
		$sDecryptedUser =  $saDecrypted[0]; // Get Username from Token
		$sDecryptedDT =  strtotime($saDecrypted[1]); // Get Date Time from Token
		$CDT = strtotime(date("Y-m-d H:i:s")); // Current Date Time
		$DTD = round(abs($sDecryptedDT - $CDT) / 60,2); // Date Time Difference
		
		if ($DTD <= 2)
			{
				echo '<p>' . $DTD . ' minute(s)</p>';
				echo '<p>Current Date Time: ' .$CDT .'</p>';
				echo '<p>Decrypted: '.$decrypted.'</p>';
				echo '<p>Username: ' . $sDecryptedUser .'</p>';
			}
		else
			{
				echo 'Too Long';
				echo '<p>' . $DTD . ' minute(s)</p>';
				
				echo '<p>Current Date Time: ' .$CDT .'</p>';
				//echo '<p>Decrypted: '.$decrypted.'</p>';
				//echo '<p>Username: ' . $sDecryptedUser .'</p>';
			}
	}
?>
All information on this site is shared with the intention to help. Before any source code or program is ran on a production (non-development) system it is suggested you test it and fully understand what it is doing not just what it appears it is doing. I accept no responsibility for any damage you may do with this code.

Related

Code PHP

Post navigation

Previous post
Next post

Related Posts

MySQL Get Disk Space Allocation of Database

Posted on October 2, 2015

SELECT table_name AS "Tables" ,round(((data_length + index_length) / 1024 / 1024), 2) "Size in MB" FROM information_schema.TABLES ORDER BY (data_length + index_length) DESC SELECT table_name AS "Tables" ,round(((data_length + index_length) / 1024 / 1024), 2) "Size in MB" FROM information_schema.TABLES WHERE table_schema = "$DBNAME" ORDER BY (data_length + index_length) DESC…

Read More

Mac OSX Terminal – Create SSH Key

Posted on December 20, 2022August 17, 2024

cd ~/.ssh ssh-keygen -t ed25519 -C "<email address>" -f BitBucket cat BitBucket.pub Originally Posted on December 20, 2022Last Updated on August 17, 2024 All information on this site is shared with the intention to help. Before any source code or program is ran on a production (non-development) system it is…

Read More

Remotely Find Raspberry Pi IP

Posted on October 13, 2015October 13, 2015

First install nmap sudo apt-get install nmap Then run IP addr show and look for something like ‘inet 10.1.1.68/24 brd 10.1.1.255’ ip addr show eth0 Now based on the inet IP CIDR type sudo nmap -sn 10.1.1.68/24 You should see something like this Nmap scan report for 10.1.1.54 Host is…

Read More

Code

Top Posts & Pages

  • PowerShell - Rename Pictures to Image Taken
  • Front Page
  • C# - Start/Stop/Restart Services
  • MacPorts / HomeBrew - Rip CD tracks from terminal
  • PowerShell - Show File Extensions

Recent Posts

  • Javascript – Digital Clock with Style
  • BASH – Web Ping Log
  • BASH – Picture / Video File Name Manipulation
  • Mac OSX Terminal – Create SSH Key
  • Bash – Rename Picture

Top Posts

  • PowerShell - Rename Pictures to Image Taken
  • C# - Start/Stop/Restart Services
  • MacPorts / HomeBrew - Rip CD tracks from terminal
  • PowerShell - Show File Extensions
  • Open On Screen Keyboard (OSK)
  • SQLite - Auto-Increment / Auto Generate GUID
©2025 David Kittell | WordPress Theme by SuperbThemes