$module = mcrypt_module_open(MCRYPT_DES, '', MCRYPT_MODE_CBC, '');
if($module === false)
die("DES module could not be opened");
$blockSize = mcrypt_get_block_size(MCRYPT_DES, MCRYPT_MODE_CBC);
The $blockSize variable is used later for padding and padding removal using pkcs7. Next to encrypt data I had to implement the following:
//encryption
$key = substr($key, 0, 8);
$iv = $key;
$rc = mcrypt_generic_init($module, $key, $iv);
//apply pkcs7 padding
$value_length = strlen($value);
$padding = $blockSize - ($value_length % $blockSize);
$value .= str_repeat( chr($padding), $padding);
$value = mcrypt_generic($module, $value);
$value = base64_encode($value);
mcrypt_generic_deinit($module);
//value now encrypted
Basically, the encryption scheme the .NET side was using was set the iv to the key, pad data, encrypt data, then base64 encode data. So here I've done the same thing in PHP. Now I needed to do the exact same thing for decryption:
//Decryption
$key = substr($key, 0, 8);
$iv = $key;
$rc = mcrypt_generic_init($module, $key, $iv);
$value = base64_decode($value);
$value = mdecrypt_generic($module, $value);
//apply pkcs7 padding removal
$packing = ord($value[strlen($value) - 1]);
if($packing && $packing < $this->_blockSize){
for($P = strlen($value) - 1; $P >= strlen($value) - $packing; $P--){
if(ord($value{$P}) != $packing){
$packing = 0;
}//end if
}//end for
}//end if
$value = substr($value, 0, strlen($value) - $packing);
mcrypt_generic_deinit($module);
//value now decrypted
This is basically the same as encryption but in reverse. The only real difference is the pkcs7 padding removal. Hopefully this tidbit helps a few others out there who run into encrypt and decryption issues between .NET and PHP.
