Liam
Liam

Reputation: 47

PHP encryption using OpenSSL

I have been trying to write two functions that will encrypt and decrypt my data, as I'm storing some information that I don't want going into database in plain text. The function that encrypts works fine. But I don't know why the decryption doesn't bring back the plain text?

Is there something I have done wrong?

<?php
$string = "This is my string!";

$encryption_key = "DVF0!LoQs2bPyTvSF0epXPFStbIn!057";
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length(AES_256_CBC));

function encryptString($encryption_key, $iv, $string) {
    define('AES_256_CBC', 'aes-256-cbc');
    $encrypted = openssl_encrypt($string, AES_256_CBC, $encryption_key, 0, $iv);
    return $encrypted;
}

function decryptString($encryption_key, $iv, $encrypted) {
    define('AES_256_CBC', 'aes-256-cbc');
    $encrypted = $encrypted . ':' . $iv;
    $parts = explode(':', $encrypted);
    $decrypted = openssl_decrypt($parts[0], AES_256_CBC, $encryption_key, 0, $parts[1]);
    return $decrypted;
}

$encryptstring = encryptString($encryption_key, $iv, $string);
$decryptstring = decryptString($encryption_key, $iv, $encryptstring);
?>

Original: <? print $string; ?>
Encryption Key: <?php print $encryption_key; ?>
Encrypted func: <?php print $encryptstring; ?>
Decrypted func: <?php print $decryptstring; ?>

Upvotes: 0

Views: 605

Answers (1)

Forbs
Forbs

Reputation: 1276

Your encryption key changes with each function call using openssl_random_pseudo_bytes

Make the key static such as $encryption_key = "XXXX"; or global the variable and only call it once.

Don't forget to apply that to your $iv as well.

Upvotes: 3

Related Questions