Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make openssl_encrypt pad the input to the required block size?

My code works if I manually pad my string to the length of 32.
My question is: Is there a way to make the openSSL pad the data, or do I always have to do it for it?

Working:

 openssl_encrypt ("my baba is over the ocean1111111", 'AES-256-CBC', $MY_SECRET_KEY,OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING,$MY_IV);

Not working:

openssl_encrypt ("my baba is over the ocean", 'AES-256-CBC', $MY_SECRET_KEY,OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING,$MY_IV);

I solve this currently by self padding:

$pad = 32 - (strlen("my baba is over the ocean") % 32);
$clear = "my baba is over the ocean" . str_repeat(chr($pad), $pad); //encrypt this string
like image 845
Itay Moav -Malimovka Avatar asked Feb 13 '17 19:02

Itay Moav -Malimovka


People also ask

What is IV in Openssl_encrypt?

An initialization vector (IV) is an arbitrary number that can be used with a secret key for data encryption to foil cyber attacks. This number, also called a nonce (number used once), is employed only one time in any session to prevent unauthorized decryption of the message by a suspicious or malicious actor.

What padding does OpenSSL use?

In fact, for plaintext padding, OpenSSL uses PKCS padding (which is documented), so it's extra confusing that it's using zero-padding here. In any case, follow the advice from the stackoverflow answer and don't rely on this padding – always provide the key and IV in the right size.

What is openssl_ encrypt in php?

In PHP, Encryption and Decryption of a string is possible using one of the Cryptography Extensions called OpenSSL function for encrypt and decrypt. openssl_encrypt() Function: The openssl_encrypt() function is used to encrypt the data.

What is Openssl_raw_data?

OPENSSL_RAW_DATA just tells openssl_encrypt() to return the cipherText as ... raw data. By default, it returns it Base64-encoded. The source code is easy to find, but not really useful as it's not like the flag does anything extra ... The opposite - it tells PHP not to do the extra step of Base64 encoding.


1 Answers

As Luke Park said, instead of explicitly telling openssl_encrypt to use OPENSSL_ZERO_PADDING, simply remove that option from the parameter and it will default to the PKCS #7 padding scheme (fills the rest of the block with 0x0n where n is the number of bytes necessary; + 16 0x00 if the block is already complete). Note: PKCS #5 as referenced by Luke and PKCS #7 are effectively identical in this scenario.

From PHP docs:

Without using OPENSSL_ZERO_PADDING, you will automatically get PKCS#7 padding.

So you should be calling:

openssl_encrypt("my baba is over the ocean", 'AES-256-CBC', $MY_SECRET_KEY, OPENSSL_RAW_DATA, $MY_IV);
like image 136
Andy Avatar answered Sep 20 '22 02:09

Andy