PHP Encryption Method Comparison -


i asked create method encryption / decryption of url string. produced 1 liner , shot out.

i provided code developer , asked opinion. looked @ find more complex function.

my questions:

what specific differences here?

are there shortfalls found in short solution?

we encrypting json encoded array , passing via query string url.

long solution:

public function encrypt($message, $key = 'defaultkey') {      //create instance of mcrypt resource     $td = mcrypt_module_open('tripledes', '', 'ecb', '');      //create random intialization vector , initialize     $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), mcrypt_rand);     mcrypt_generic_init($td, $key, $iv);      // create timestamp , add it.     $t = new \datetime('now');     $message = $t->format("ymdhis") . $message;      // pkcs7 padding     //get block size of cipher     $b = mcrypt_get_block_size('tripledes', 'ecb');      //what purpose?     $datapad = $b-(strlen($message)%$b);     $message .= str_repeat(chr($datapad), $datapad);      //convert hexidec string     $encrypted_data = bin2hex(mcrypt_generic($td, $message));     mcrypt_generic_deinit($td);     mcrypt_module_close($td);     return $encrypted_data; } 

short solution:

public function encrypt($message, $key = 'defaultkey') {      $t = new \datetime('now');     return bin2hex(mcrypt_encrypt(mcrypt_3des, $key, $t->format("ymdhis").$message, 'ecb')); } 

the real difference padding. triple des symmetric block cipher , such operates on single full block (8 byte). mode of operation ecb enables encrypt many full blocks. when data not multiple of block size, has padded encrypted.

mcrypt uses 0 padding default. fill plaintext 0x00 bytes until multiple of block size reached. additional padding bytes have removed during decryption (usually done rtrim()). means if plaintext ends 0x00 bytes, removed might break plaintext.

pkcs#5/pkcs#7 padding on other hand pads byte represents number of padding bytes. if plaintext multiple of block size, add full block of padding. doing way enables remove padding , not additional plaintext bytes during decryption.

whether mcrypt_generic_init() or mcrypt_encrypt() used doesn't make difference.


you should never use ecb mode. not semantically secure. means same plaintext block result in same ciphertext block. since you're encrypting urls first couple of blocks stay same similar urls after observing many ciphertexts. attacker might additional information out of this.

use @ least cbc mode random iv. iv doesn't need hidden, can prepended ciphertext , sliced off during decryption.

it best have ciphertext authenticated detect manipulation. can use message authentication code such hmac-sha256 different key. better way use authenticated mode such gcm or eax.


Comments

Popular posts from this blog

css - SVG using textPath a symbol not rendering in Firefox -

Java 8 + Maven Javadoc plugin: Error fetching URL -

datatable - Matlab struct computations -