Reputation: 122
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.)
Upvotes: 0
Views: 874
Reputation: 269
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
Upvotes: 1
Reputation: 61952
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.
Upvotes: 1