Reputation: 2448
I have a big array of data (~2000 strings with 2000 chars each) to encrypt using symetric encryption AES.
My code is currently the following :
Encryption function
function encryptAES($content, $key) {
$iv = mcrypt_create_iv(256, MCRYPT_DEV_RANDOM);
$iv_base64 = rtrim(base64_encode($iv), '=');
$encrypted = base64_encode(mcrypt_encrypt(
MCRYPT_RIJNDAEL_256,
$key,
$content . md5($content),
MCRYPT_MODE_CBC,
$iv
);
return $iv_base64 . $encrypted;
}
Array Encryption
foreach ($fields as $field) {
$field['encryptedValue'] = encryptAES($field['value'], $SymKey);
}
.
Only strings can be passed to $content. And this code might be slow if I just make a loop over the thousands strings.
Can you suggest a more performant way ?
Upvotes: 1
Views: 750
Reputation: 44376
serialize()
your array. The result of serialization is a binary string, which is acceptable by mcrypt_encrypt
.
Encrypt serialized array with one function call, and base64
the result:
$myArray = [ ... ];
$content = serialize($myArray);
$iv = mcrypt_create_iv(256, MCRYPT_DEV_RANDOM);
$encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $content, MCRYPT_MODE_CBC, $iv);
There is no need for base64 encription of data passed to mcrypt_encrypt
.
Upvotes: 2