I need a combination of functions that does:
- array serialization(no object, small - 3-7 key-value pairs of strings, no references)
- data validity check of above(Is it better for the hash to be inside the array?)
- encryption of above(is there any encryption method that validates decrypted information?)
- compression of above(I am not sure if the cost worth: bandwidth / CPU time)
...of an array.
Everything should be optimized for speed.
For serializing the array I was thinking about using json_encode() rather than serialize() because it's faster. See Preferred method to store PHP arrays (json_encode vs serialize).
For data validity check I was thinking about using sha1(), but I am considering crc32 because it's faster and I don't think collisions are close. See Fastest hash for non-cryptographic uses?.
For encryption i made:
<?php
function encode($pass, $data) {
return mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $pass, $data, MCRYPT_MODE_ECB);
}
function decode($pass, $data) {
return mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $pass, $data, MCRYPT_MODE_ECB);
}
$rand = str_repeat(rand(0, 1000), 5);
$start = microtime(true);
for($i = 0; $i <= 10000; $i++){
encode('pass', $rand);
}
echo 'Script took ' . (microtime(true) - $start) . ' seconds for encryption<br/>';
$start = microtime(true);
for($i = 0; $i <= 10000; $i++){
encode('pass', $rand);
}
echo 'Script took ' . (microtime(true) - $start) . ' seconds for decryption';
Results are:
Script took 1.8680129051208 seconds for encryption
Script took 1.8597548007965 seconds for decryption
I would rather avoid any randomness. I know that CBC mode is more secure, but it is also slower.
For compression I have no idea what is better to use given the fact that the resulting string is binary and short.
Is there any compression that don't require encoding in order to set the resulting string as a cookie? I know that sha1() for example returns only digits ans letters.
It is a complex question. So feel free to point anything wrong or not accurate. It contains many topics but basically the short question is how to safely and rapidly encrypt/decrypt an array while having a small representation of it.
Is this the right order?
Is data validation required given that there is a high probability that the resulting JSON
won't be valid in case data is altered?
Is there a function that already combines those or some of those functions?