Simple PHP Encryption / Decryption (Mcrypt, AES)

21,200

Solution 1

I'm recently learning about this subject, and am posting this answer as a community wiki to share my knowledge, standing to be corrected.

It's my understanding that AES can be achieved using Mcrypt with the following constants as options:

MCRYPT_RIJNDAEL_128     // as cipher
MCRYPT_MODE_CBC         // as mode
MCRYPT_MODE_DEV_URANDOM // as random source (for IV)

During encryption, a randomized non-secret initialization vector (IV) should be used to randomize each encryption (so the same encryption never yields the same garble). This IV should be attached to the encryption result in order to be used later, during decryption.

Results should be Base 64 encoded for simple compatibility.

Implementation:

<?php

define('IV_SIZE', mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC));

function encrypt ($key, $payload) {
  $iv = mcrypt_create_iv(IV_SIZE, MCRYPT_DEV_URANDOM);
  $crypt = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $payload, MCRYPT_MODE_CBC, $iv);
  $combo = $iv . $crypt;
  $garble = base64_encode($iv . $crypt);
  return $garble;
}

function decrypt ($key, $garble) {
  $combo = base64_decode($garble);
  $iv = substr($combo, 0, IV_SIZE);
  $crypt = substr($combo, IV_SIZE, strlen($combo));
  $payload = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $crypt, MCRYPT_MODE_CBC, $iv);
  return $payload;
}


//:::::::::::: TESTING ::::::::::::


$key = "secret-key-is-secret";
$payload = "In 1435 the abbey came into conflict with the townspeople of Bamberg and was plundered.";

// ENCRYPTION
$garble = encrypt($key, $payload);

// DECRYPTION
$end_result = decrypt($key, $garble);

// Outputting Results
echo "Encrypted: ", var_dump($garble), "<br/><br/>";
echo "Decrypted: ", var_dump($end_result);

?>

Output looks like this:

Encrypted: string(152) "4dZcfPgS9DRldq+2pzvi7oAth/baXQOrMmt42la06ZkcmdQATG8mfO+t233MyUXSPYyjnmFMLwwHxpYiDmxvkKvRjLc0qPFfuIG1VrVon5EFxXEFqY6dZnApeE2sRKd2iv8m+DiiiykXBZ+LtRMUCw==" 

Decrypted: string(96) "In 1435 the abbey came into conflict with the townspeople of Bamberg and was plundered."

Solution 2

Add function to clean control characters (�).

function clean($string) {
return preg_replace('/[\x00-\x09\x0B\x0C\x0E-\x1F\x7F]/', '', $string);

}

echo "Decrypted: ", clean($end_result);

Sentrapedagang.com

Share:
21,200
ChaseMoskal
Author by

ChaseMoskal

I'm a web developer.

Updated on July 05, 2022

Comments

  • ChaseMoskal
    ChaseMoskal almost 2 years

    I'm looking for a simple yet cryptographically strong PHP implementation of AES using Mcrypt.

    Hoping to boil it down to a simple pair of functions, $garble = encrypt($key, $payload) and $payload = decrypt($key, $garble).