简体   繁体   中英

AES-256 in PHP and securely storing keys?

I have the following code...

   $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
   $iv = mcrypt_create_iv($iv_size, MCRYPT_DEV_URANDOM);
   $key = pack("H*", "Insert64CharacterStringHere");

   $value = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $value, MCRYPT_MODE_CBC, $iv);

   $value = $iv . ":" . $value;

I'm using this to encrypt data in AES-256 on my site. I store the initialization vector with the data being encrypted, and between the data and the initialization vector is a colon so that I can explode the string later into the initialization vector and the data, then decrypt.

What I'm wondering about is where to store the key. If I store it on the same database, it's almost as insecure as simply leaving the data unencrypted. I have a feeling leaving the key lying around somewhere in my PHP code is just as insecure.

Where should the key be stored? Is this an appropriate way to store the initialization vector? Am I safe using the colon as a deliminator? IE will the initialization vector or the data ever contain a colon?

Partial answer...

Is this an appropriate way to store the initialization vector? Am I safe using the colon as a deliminator? IE will the initialization vector or the data ever contain a colon?

The IV is always 16 bytes for AES (in CBC mode). There is no need to have a delimiter. You can safely use the substr() function to split the IV and the ciphertext before decryption:

$iv = substr($encrypted, 0, 16);
$ct = substr($encrypted, 16);

If you're in a multibyte string environment, you should use mb_substr() like this :

$iv = mb_substr($encrypted, 0, 16, '8bit');
$ct = mb_substr($encrypted, 16, mb_strlen($encrypted, '8bit'), '8bit');

In fact, since the IV is randomly generated, it may contain a colon at some point in time. Expected value is 1 for every 16 encryptions. It doesn't matter whether the data contains a colon, since you're probably searching from the beginning.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM