How does a specific encryption algorithm work if the data is empty

Viewed 61

Where is the encryption based on if the string which should be encrypted is empty?

$string = ''; // empty string

$met_enc = 'aes256';  
$key_enc = '1234'; 
$iv = '1234567891011121'; // 16 chars

$encryption = openssl_encrypt($string, $met_enc, $key_enc, 0, $iv); // encrypt string
$decryption = openssl_decrypt($encryption, $met_enc, $key_enc, 0, $iv); // decrypt string

echo 'Encrypted name: '.$encryption.'<br />'; 
echo 'Original name: '.$decryption.'<br />'; 

Code above outputs:

Encrypted name: NMPSQ1v5tCTFn9tazrsSQA==
Original name:

Can someone explain me where the encryption is generated from? Because the string is empty...

1 Answers

What is necessary to encrypt plaintexts of arbitrary length with AES?

AES is a block cipher and as such only encrypts plaintexts that are exactly as long as its block size (16 bytes). A mode of operation like ECB or CBC enables you to encrypt a multiple of the block size. Finally, in order to encrypt a message that is not necessarily a multiple of the block size padding must be applied to reach the next multiple of the block size. 0 bytes is already a multiple, so a full block of padding is added to reach the next multiple which is 16 bytes.

If PKCS#5/PKCS#7 padding (and a few others) is used, it is important to always add padding because the padding determines how many bytes must be removed when decrypting. If no padding was applied during encryption, the decryption procedure must not remove any bytes.

Which encryption method does your code use?

Your code is using AES in CBC mode with implicit PKCS#7 padding.

There are exceptions

There are other modes of operation such as CTR that don't require padding and as such can encrypt messages of arbitrary length on their own.

ZeroPadding is done by filling the plaintext with 0x00 bytes to a multiple of the block size. Some implementations add a full block and some add nothing when the message is already a multiple of the block size.


Security considerations:

Don't confuse keys and passwords. Your key is too short and openssl_encrypt will fill it up with 0x00 bytes to reach the requested key size (32 byte or 256 bit in your case). Passwords should be hashed multiple times to derive a key.

Related