I am trying to Use the Padding Mode: Zeros in AES-256-ECB encryption
but when i use OPENSSL_ZERO_PADDING
it does not return anything.
this is the code :
$plaintext = "The quick brown fox jumps over the lazy dog"; $key = 'd61d2cd58d01b234e1800938erf8467k'; $chiperRaw = openssl_encrypt($plaintext, $cipher, $key, OPENSSL_ZERO_PADDING); $ciphertext = trim(base64_encode($chiperRaw)); echo($ciphertext);
But when i use OPENSSL_RAW_DATA
instead of OPENSSL_ZERO_PADDING
it returns the encrypted string
Why isnt the OPENSSL_ZERO_PADDING
working ? how can i fix this ?
Advertisement
Answer
What do you know, I’m Sam too!
It looks like OPENSSL_NO_PADDING
won’t work if the input data is not a multiple of the blocksize. You can fix this by padding the plaintext yourself:
$cipher = 'AES-256-ECB'; $key = 'd61d2cd58d01b234e1800938erf8467k'; $plaintext = "The quick brown fox jumps over the lazy dog"; if (strlen($plaintext) % 8) { $plaintext = str_pad($plaintext, strlen($plaintext) + 8 - strlen($plaintext) % 8, ""); } $chiperRaw = openssl_encrypt($plaintext, $cipher, $key, OPENSSL_NO_PADDING); $ciphertext = trim(base64_encode($chiperRaw)); echo($ciphertext);
This will get your what you’re looking for, but I think the best option for you (if you’re not absolutely required to pad the string), is to use the 5th parameter of openssl_encrypt
and pass an IV
like the following (note the switch back to OPENSSL_RAW_DATA
):
$cipher = 'AES-256-ECB'; $key = 'd61d2cd58d01b234e1800938erf8467k'; $iv_size = openssl_cipher_iv_length( $cipher ); $iv = openssl_random_pseudo_bytes( $iv_size ); $plaintext = "The quick brown fox jumps over the lazy dog"; $chiperRaw = openssl_encrypt($plaintext, $cipher, $key, OPENSSL_RAW_DATA, $iv); $ciphertext = trim(base64_encode($chiperRaw)); echo($ciphertext);
There’s great summary of why you should use an iv here: What is an openssl iv, and why do I need a key and an iv?