ChaseMoskal
ChaseMoskal

Reputation: 7681

Simple PHP Encryption / Decryption (Mcrypt, AES)

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).

Upvotes: 3

Views: 22406

Answers (4)

Abhijit Srivastava
Abhijit Srivastava

Reputation: 1459

Class Mycrypt

Try using this class. Here. All you need to pass is key and string.

class MCrypt
{
    const iv = 'fedcba9876543210';

    /**
 * @param string $str
 * @param bool $isBinary whether to encrypt as binary or not. Default is: false
 * @return string Encrypted data
 */
public static function encrypt($str, $key="0123456789abcdef", $isBinary = false)
{
    $iv = self::iv;
    $str = $isBinary ? $str : utf8_decode($str);
    $td = mcrypt_module_open('rijndael-128', ' ', 'cbc', $iv);
    mcrypt_generic_init($td, $key, $iv);
    $encrypted = mcrypt_generic($td, $str);
    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);
    return $isBinary ? $encrypted : bin2hex($encrypted);
}

/**
 * @param string $code
 * @param bool $isBinary whether to decrypt as binary or not. Default is: false
 * @return string Decrypted data
 */
public static function decrypt($code, $key="0123456789abcdef", $isBinary = false)
{
    $code = $isBinary ? $code : self::hex2bin($code);
    $iv = self::iv;
    $td = mcrypt_module_open('rijndael-128', ' ', 'cbc', $iv);
    mcrypt_generic_init($td, $key, $iv);
    $decrypted = mdecrypt_generic($td, $code);
    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);
    return $isBinary ? trim($decrypted) : utf8_encode(trim($decrypted));
}

private static function hex2bin($hexdata)
{
    $bindata = '';
    for ($i = 0; $i < strlen($hexdata); $i += 2) {
        $bindata .= chr(hexdec(substr($hexdata, $i, 2)));
    }
    return $bindata;
}
   }

How To Use

 $var = json_encode(['name'=>['Savatar', 'Flash']]);
 $encrypted = MCrypt::encrypt();
 $decrypted = MCrypt::decrypt($encrypted);

Upvotes: -1

Dewa Putra
Dewa Putra

Reputation: 15

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

Upvotes: 1

T.Todua
T.Todua

Reputation: 56537

Simple and Usable:

$text= 'Hi, i am sentence';
$secret = 'RaNDoM cHars!@#$%%^';

$encrypted = simple_encrypt($text,           $secret);
$decrypted = simple_decrypt($encrypted_text, $secret);

codes:

function simple_encrypt($text_to_encrypt, $salt)    { 
    return trim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128,  pack('H*', $salt), $text_to_encrypt, MCRYPT_MODE_CBC, $iv =  mcrypt_create_iv($iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), MCRYPT_RAND))));
}

function simple_decrypt($encrypted, $salt)  { 
    return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, pack('H*', $salt), base64_decode($encrypted), MCRYPT_MODE_CBC, $iv = mcrypt_create_iv($iv_size=mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), MCRYPT_RAND))); 
}

Upvotes: 0

ChaseMoskal
ChaseMoskal

Reputation: 7681

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."

Upvotes: 12

Related Questions