mcrypt 2 vie problema cifratura con codifica base64 e serializzazione
-
19-09-2019 - |
Domanda
UPDATE (soluzione)
Dal momento che questo post sembra ottenere discreta quantità di attenzione, mi piacerebbe farvi sapere che la soluzione è stato quello di fornire un parametro adeguato enctype
(tipo di contenuto) nella dichiarazione <FORM>
. È necessario impostare il valore a multipart/form-data
per evitare che codifica che altrimenti avvenire utilizzando l'enctype predefinito di application/x-www-form-urlencoded
. Un piccolo estratto qui di seguito da Forme in documenti HTML a w3.org:
Il tipo di contenuto "Application / x-www-form-urlencoded" è inefficiente per l'invio di grandi dimensioni quantità di dati binari o di testo contenenti caratteri non-ASCII. Il tipo di contenuto "multipart / form-data" deve essere utilizzato per la presentazione delle forme che contengono i file, i dati non ASCII, e dati binari.
Ed ecco la dichiarazione di forma corretta:
<FORM method="POST" action="/path/to/file/" name="encryptedForm" enctype="multipart/form-data">
domanda iniziale
Sto lavorando ad una classe di protezione sotto forma di spam che sostituisce essenzialmente i nomi dei campi modulo con un valore crittografato utilizzando mcrypt. Il problema di questo è che la crittografia mcrypt non si limita al solo caratteri alfanumerici, che potrebbero invalidare i campi del modulo. Dato il codice qui sotto, si può pensare di qualsiasi ragione per la quale mi sarei avendo problemi decifrare i valori dell'array già cifrata?
/**
* 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;
}
In seguito ho faccio impostazione di una chiamata il valore di un elemento di modulo nascosto utilizzando:
base64_encode(serialize(self::$encrypted))
Essenzialmente il campo nascosto contiene una matrice di tutti i campi di modulo che sono stati cifrati con il loro valore crittografato. Questo è quindi so quali campi devono essere decifrati sul backend. Al modulo di presentazione questo campo viene analizzato sul backend con il seguente codice:
// 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;
I miei tentativi di decifrare il campo di forma cifrata chiavi stanno fallendo. E 'semplicemente la creazione di una nuova chiave confuso nella matrice $_POST
. La mia ipotesi è che sia base64_encoding
o serialization
è spogliando caratteri dal $encrypted_data
. Qualcuno potrebbe verificare se questo è il colpevole e se ci sono metodi alternativi per i tasti di forma di codifica?
Soluzione
Così ho preso il codice, e modificato un po 'in modo che possa rimuovere l'elemento di una richiesta POST e la funzione sembra funzionare bene. Se si prende il codice che ho postato e creare uno script con esso, dovrebbe funzionare nella CLI e vedrete la sua codificare / decodificare correttamente i campi. Ciò dovrebbe significare che la richiesta post è in qualche modo garbling i dati crittografati / serializzati / codificati. Se si utilizza un quadro, vorrei guardare più nel modo in cui gestisce la matrice posta in quanto potrebbe alterare le chiavi / valori inducendoli a non corrispondono. Il codice che hai postato sembra che vada bene.
<?php
/**
* Two way encryption function to encrypt/decrypt keys with
* the DES encryption algorithm.
*/
function encryption($text, $encrypt = true, &$encryptedFields = array())
{
$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('sdf234d45)()*5gf512/?>:LPIJ*&U%&^%NBVFYUT^5hfhgvkjtIUUYRYT', 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;
$encryptedFields[] = $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;
}
$encryptedFields = array();
// encrypt some form fields
encryption('firstname', true, $encryptedFields);
encryption('lastname', true, $encryptedFields);
encryption('email_fields', true, $encryptedFields);
echo "Encrypted field names:\n";
print_r($encryptedFields);
// create a usable string of the encrypted form fields
$hiddenFieldStr = base64_encode(serialize($encryptedFields));
echo "\n\nFull string for hidden field: \n";
echo $hiddenFieldStr . "\n\n";
$encPostFields = unserialize(base64_decode($hiddenFieldStr));
echo "\n\nDecrypted field names:\n";
foreach($encPostFields as $field)
{
echo encryption($field, false)."\n";
}
?>