dongyou2714 2015-07-07 13:33 采纳率: 0%
浏览 109

Blowfish CBC加密不解密

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) . "
";
    echo 'DATA: ' . bin2hex($crypttext) ."
" ;
}

$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

  • 写回答

2条回答 默认 最新

  • dtup3446 2015-07-07 13:56
    关注

    I ended up using a simpler library which supperts cbc mode in a very simple fashion.

    http://jaryl-lan.blogspot.de/2014/07/openfire-blowfish-encryptiondecryption.html

    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog