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

zaph
  • 111,848
  • 21
  • 189
  • 228
Liam
  • 47
  • 8
  • 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 Mar 30 '17 at 15:14
  • Further to the above comment, you can take the ampersand out of `& encryptString` and `& decryptString`. – halfer Mar 30 '17 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? – zaph Mar 30 '17 at 16:47

1 Answers1

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.

Forbs
  • 1,256
  • 1
  • 7
  • 9
  • i have made my key static, i dont see what i need to change in $iv – Liam Mar 30 '17 at 15:29
  • $iv is also a `openssl_random_pseudo_bytes`, hence it has different values with the encrypt and the decrypt. – Forbs Mar 30 '17 at 15:30
  • 2
    @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. – zaph Mar 30 '17 at 15:31
  • 1
    See this link for some help on how that works http://stackoverflow.com/questions/39412760/what-is-an-openssl-iv-and-why-do-i-need-a-key-and-an-iv – Forbs Mar 30 '17 at 15:32