0

Hoping someone can shed some light on this.

I am updating some older code which uses the mcrypt_generic function, utilizing a DES-CBC cipher

When I update this code to use the openssl_encrypt, I get the same output, but with 8 bytes appended to the end of my encoded string.

Before

$this->_cipher = mcrypt_module_open(MCRYPT_DES, '', MCRYPT_MODE_CBC,'');
mcrypt_generic_init($this->_cipher, $this->_key, $this->_iv) 
mcrypt_generic($this->_cipher, $text)

Before method output:

27049189e7e08db6

After

openssl_encrypt($text, "DES-CBC", $this->_key,  OPENSSL_RAW_DATA , $this->_iv);

After method output:

27049189e7e08db6d504d16516e1c567

Why is this happening, and what (other then a substring) can be done to prevent it?

Señor Reginold Francis
  • 16,318
  • 16
  • 57
  • 73
  • Possibly related: https://stackoverflow.com/questions/48800725/convert-mcrypt-generic-to-openssl-encrypt – Script47 Sep 11 '19 at 14:40
  • 1
    I would look into the padding. Since openssl is a modern library it probably uses modern padding standards (like PKCS#7) and mcrypt could use an older technique (like zero padding). I don't know for sure but I had a similar problem and I think it was the padding that was different. – LLJ97 Sep 11 '19 at 14:50

2 Answers2

2

According to this:

1.3. Data Size

The DES algorithm operates on blocks of eight octets. This often requires padding after the end of the unencrypted payload data.

It's possible that it's simply padding the input.

mcrypt_encrypt() seems to pad by 0 by default (based on code example in docs):

# creates a cipher text compatible with AES (Rijndael block size = 128)
# to keep the text confidential 
# only suitable for encoded input that never ends with value 00h
# (because of default zero padding)
$ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key,
$plaintext, MCRYPT_MODE_CBC, $iv);

which would explain the difference in length.

Community
  • 1
  • 1
treyBake
  • 6,440
  • 6
  • 26
  • 57
1

So I manage to find a solution

openssl_encrypt($text, "DES-CBC", $this->_key,  OPENSSL_NO_PADDING, $this->_iv);

This mode,

OPENSSL_NO_PADDING

seems to produce the output I was expecting

Señor Reginold Francis
  • 16,318
  • 16
  • 57
  • 73