I am working on a form spam protection class which essentially replaces form field names with an encrypted value using mcrypt. The problem with this is that mcrypt encryption is not limited to only alphanumeric characters which would invalidate form fields. Given the code below, can you think of any reason why I'd be having problems decrypting the values of the already encrypted array?
/**
* Two way encryption function to encrypt/decrypt keys with
* the DES encryption algorithm.
*/
public static function encryption($text, $encrypt = true)
{
$encrypted_data = '';
$td = mcrypt_module_open('des', '', 'ecb', '');
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
if (mcrypt_generic_init($td, substr(self::$randomizer, 16, 8), $iv) != -1) {
if ($encrypt) {
// attempt to sanitize encryption for use as a form element name
$encrypted_data = mcrypt_generic($td, $text);
$encrypted_data = base64_encode($encrypted_data);
$encrypted_data = 'i' . strtr($encrypted_data, '+/=', '-_.');
self::$encrypted[] = $encrypted_data;
} else {
// reverse form element name sanitization and decrypt
$text = substr($text, 1);
$text = strtr($text, '-_.', '+/=');
$text = base64_decode($text);
$encrypted_data = mdecrypt_generic($td, $text);
}
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
}
return $encrypted_data;
}
I later make a call setting a hidden form element's value using:
base64_encode(serialize(self::$encrypted))
Essentially the hidden field contains an array of all form fields which were encrypted with their encrypted value. This is so I know which fields need to be decrypted on the backend. Upon form submission this field gets parsed on the backend with the following code:
// load the mapping entry
$encrypted_fields = $input->post('encrypted', '');
if (empty($encrypted_fields)) {
throw new AppException('The encrypted form field was empty.');
}
// decompress array of encrypted fields
$encrypted_fields = @unserialize(base64_decode($encrypted_fields));
if ($encrypted_fields === false) {
throw new AppException('The encrypted form field was not valid.');
}
// get the mapping of encrypted keys to key
$data = array();
foreach ($_POST as $key => $val) {
// if the key is encrypted, add to data array decrypted
if (in_array($key, $encrypted_fields)) {
$decrypted = self::encryption($key, false);
$data[$decrypted] = $val;
unset($_POST[$key]);
} else {
$data[$key] = $val;
}
}
// merge $_POST array with decrypted key array
$_POST += $data;
My attempts to decrypt the encrypted form field keys are failing. It's simply creating a new garbled key in the $_POST
array. My guess is that either base64_encoding
or serialization
is stripping chars from the $encrypted_data
. Could somebody verify if this is the culprit and whether there are any alternative methods for encoding form keys?