0
votes

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; ?>

1
What PHP version are you using? Don't you get a Strict Standards: Only variables should be assigned by reference notice? - Álvaro González
Further to the above comment, you can take the ampersand out of & encryptString and & decryptString. - halfer
1. Is the IV 16-bytes? 2. Add the encrypted data. 3. Why do you think the encryption works fine given that decryption does not work? - zaph

1 Answers

3
votes

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.