0

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

3
  • 1
    What PHP version are you using? Don't you get a Strict Standards: Only variables should be assigned by reference notice? Commented Mar 30, 2017 at 15:14
  • Further to the above comment, you can take the ampersand out of & encryptString and & decryptString. Commented Mar 30, 2017 at 15:25
  • 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? Commented Mar 30, 2017 at 16:47

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

i have made my key static, i dont see what i need to change in $iv
$iv is also a openssl_random_pseudo_bytes, hence it has different values with the encrypt and the decrypt.
@Liam The IV needs to be the same for encryption and decryption, a common solution is to prefix the encrypted data with the IV, on decryption split the data into the IV and encrypted data. The IV does not need to be secret.
See this link for some help on how that works stackoverflow.com/questions/39412760/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.