0

I have found the following decrypt function online. Other decrypt functions that I have found are a varation of this function:

public function Decrypt($data) {
    $crypt = base64_decode($data);
    $iv_size = mcrypt_get_iv_size($this->Algo, MCRYPT_MODE_ECB);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    $decrypt = mcrypt_decrypt($this->Algo, $this->Key, $crypt, MCRYPT_MODE_ECB, $iv);

    $block = mcrypt_get_block_size('blowfish', 'ecb');
    $pad = ord($decrypt[($len = strlen($decrypt)) - 1]);
    return substr($decrypt, 0, strlen($decrypt) - $pad);
}

My question is the following: The ord() function gives the ASCII value of a character. Then this ASCII value is used in a calculation which involves the string length. Why is that the case? (It seems to me that whichever ASCII value a padding is made of should not be used together with string length.)

MrTux
  • 32,350
  • 30
  • 109
  • 146
Tom
  • 122
  • 2
  • 9
  • Does that function actually work? Also, where's the encrypt portion? – Ja͢ck Dec 08 '14 at 13:54
  • Yes, the function works. I have tested it with some mock data and the return value is always as expected. – Tom Dec 08 '14 at 13:55
  • 2
    The docs for `ord` are misleading a bit, although it is not entirely incorrect. It returns the unsigned integer value of a byte. Which correlates to ASCII.# – Flosculus Dec 08 '14 at 13:56
  • 1
    Btw, I would kindly ask you to read through [this answer](http://stackoverflow.com/questions/10916284/how-to-encrypt-decrypt-data-in-php/10945097#10945097) as well, because the function you have there is completely incompetent. – Ja͢ck Dec 08 '14 at 14:04
  • The padding consists of ASCII characters with the same value of the amount of added characters as padding. Ord is used to determine that number and remove the padding. – Hans Dubois Dec 08 '14 at 14:11

2 Answers2

1

Some modes of operation like CBC and ECB for block ciphers require a padding, because the ciphers are only defined for complete blocks. So the padding is used to fill up the plaintext until the next block border. It is also used to encode the length of the padding at the same time where every byte corresponds to the length of the padding and ord() returns the integer for this "char". This double use reduces the resulting ciphertext size by one block (where size of the padding or plaintext would be kept).

The shown padding scheme corresponds to PKCS#5/PKCS#7.

Community
  • 1
  • 1
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
1

The padding consists of ASCII characters with the same value of the amount of added characters as padding.

Ord is used to determine that number and remove the padding.

more info: http://lukieb.blogspot.nl/2013/04/making-aes256-encryption-work-same-in.html

Hans Dubois
  • 269
  • 1
  • 7