serialize()
your array. The result of serialization is a binary string, which is acceptable bymcrypt_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
.
Whats is the best way to encrypt a big array with AES in PHP?
-
16-06-2023 - |
Question
State
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);
}
.
Question
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 ?
Solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow