I'm looking for encrypt/decrypt functions that will encode numbers (0, 1, 2, ...) into strings, such that these strings will look random, and later the number could be decodes back from the string.
For example: 3 will be encrypted to ABFQWEMasdEE, and 6 will be encrypted to poad_Asd#@sad.
If I could control the number of characters in the encrypted string, and also which characters can appear there, it could be great !
UPDATE
I end up with this solution:
<?php
$key = 'secret_password';
for ($i = 100; $i < 110; $i++) {
$text = "$i";
$encrypted = encrypt($text, $key);
$decrypted = decrypt($encrypted, $key);
$decrypted = rtrim($decrypted, "\0");
$ok = ($text === $decrypted);
if (!$ok) {
exit('********** BUG BUG BUG BUG BUG ***********');
}
echo '[' . $text . '] [' . $encrypted . '] [' . $decrypted . '] ' . ($ok ? 'OK' : 'BUG BUG BUG BUG BUG BUG BUG') . '<br />';
}
exit('***** OK ******');
function encrypt($data, $key) {
$td = mcrypt_module_open('cast-256', '', 'ecb', '');
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
mcrypt_generic_init($td, $key, $iv);
$encrypted_data = mcrypt_generic($td, $data);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return base64_encode($encrypted_data);
}
function decrypt($encoded_64, $key) {
$td = mcrypt_module_open('cast-256', '', 'ecb', '');
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
mcrypt_generic_init($td, $key, $iv);
$decrypted_data = mdecrypt_generic($td, base64_decode($encoded_64));
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return $decrypted_data;
}
?>
which provides the following output:
[100] [9UA0Maq3MGp0CzMOWcpOpg==] [100] OK
[101] [Y5WKH7J1+k0bFqsGw1jmrA==] [101] OK
[102] [NqV2opJc7CNq5O3lcuWKMw==] [102] OK
[103] [1FpJhHe+vrK6aKA54VR53Q==] [103] OK
[104] [MHQoYCqL4yCI9jKg1U0UYw==] [104] OK
[105] [6Qq9aXEn46xpDgv8CvnK7Q==] [105] OK
[106] [UGk1/byT7wpoFM59Uy/pdg==] [106] OK
[107] [39kyPA49zAZsCFx3pt6bYw==] [107] OK
[108] [YccDSimEf3C0NKDaVOf4kA==] [108] OK
[109] [PfmvLfVR4+gi9y9v/6efZQ==] [109] OK
***** OK ******
The strings looks random (except the ==
at the end) and all of the same size. Not perfect solution, but good enough !
Thank you all !!