I have difficulties decrypting a blowfish encrypted string in a .net environment, that was encrypted by the mcrypt php library.
Here is the script I use to encrypt some data
<?php
function encrypt_blowfish($data, $key) {
$iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$crypttext = mcrypt_encrypt(MCRYPT_BLOWFISH, $key, $data, MCRYPT_MODE_CBC, $iv);
echo 'IV: ' . bin2hex($iv) . "\n";
echo 'DATA: ' . bin2hex($crypttext) ."\n" ;
}
$secretKey = 'somekey';
$data = 'Hello World this is an encryptiontest!';
encrypt_blowfish($data, $secretKey);
I decided to use the bouncingcastle library since it seemed to be the default choice for encryption and they had a PCL version (which I need). For testing purpose I just copy/pasted the echo'd values into my C# code.
var ivString = "34c33fed0386dda1";
var iv = Hex.Decode (ivString);
var dataString = "ced4ed218d7a1fd228f8c43ca6b83f097648811661d5510678a26953729ceccdf6d78a7695cbfe43";
var data = Hex.Decode (dataString);
var keyString = "somekey";
var key = System.Text.Encoding.UTF8.GetBytes (keyString);
var engine = new BlowfishEngine();
var cipher =new PaddedBufferedBlockCipher(new CbcBlockCipher(engine));
var keyParam = new KeyParameter(key);
cipher.Init (false, keyParam);
var outBytes = new byte[data.Length];
var len = cipher.ProcessBytes (data, 0, data.Length, outBytes, 0);
cipher.DoFinal(outBytes, len);
Console.WriteLine(System.Text.Encoding.UTF8.GetString(outBytes));
When I run this code DoFinal explodes with a "Corrupt padding block" exception. So I read about pcks7 padding which essentially fills the bytes of the original string. I calculated that for my input string and the blowfish cbc algorithm block size of 8, I would need two bytes of padding so I added "22" at the end of the string. This however yielded the same result.
Also, I don't see any point where I can insert the IV into the blowfish decryption. It feels like I am completely lacking/not understanding a vital point here. Any1 any ideas on what goes wrong here? Also if possible I would like to skip on the padding part in my php and simply decrypt with iv/passphrase in c#, is that even possible?
Cheers and thanks
Tom