简体   繁体   English

C#和PHP上的Blowfish加密会产生不同的结果

[英]Blowfish encryption on C# and PHP yields different results

I'm trying to do a Blowfish encryption, but results in decryption an C#-encrypted code are not the same. 我正在尝试进行Blowfish加密,但导致解密C#加密的代码却不一样。 I used this library in C#: https://defuse.ca/source/blowfish.cs and this self-written code to encrypt: 我在C#中使用了这个库: https//defuse.ca/source/blowfish.cs和这个自编写的加密代码:

$td = MCRYPT_BLOWFISH;
$iv_size = mcrypt_get_iv_size($td, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);

echo "Original data: $data<br />"; 

$encrypted_data = mcrypt_encrypt($td, $blowfish_key, $dec, MCRYPT_MODE_CBC, $iv);

echo "Encrypted data: " . bin2hex($encrypted_data)  . "<br />";
$x ="1e9a532f6391071e04ac46dfd4ffa1e324665ef7f1e75b8c2ea6ebabd75fd04d8"; //result from C#
$data = mcrypt_decrypt($td, $blowfish_key, $x /*$encrypted_data*/, MCRYPT_MODE_CBC, $iv);

echo trim($data); 

Could anybody help me with this issue? 有人可以帮我解决这个问题吗? Thanks in advance. 提前致谢。 CH CH

there are 2 problems in your PHP code: PHP代码中有2个问题:

first: mcrypt expects binary data ... no strings with hex encoded bytes ... (hex2bin() or pack() will convert that for you) 第一:mcrypt期望二进制数据...没有带十六进制编码字节的字符串...(hex2bin()或pack()将为你转换)

second: the IV ... your blowfish.cs generates a random IV for you, and puts that (8 bytes) in front of the cyphertext ... while your php codes generates a new random IV which will not work for decryption 第二个:IV ......你的blowfish.cs会为你生成一个随机的IV,然后把它(8个字节)放在密文的前面......而你的php代码生成一个新的随机IV,它不适用于解密

suggestion: 建议:

c# C#

var fish = new BlowFish("0000000000000000");
var cs_output=fish.Encrypt_CBC("This is a test of the blowfish.cs file");

php PHP

$cs_output="27c7c634ead1d28bfe64821a28ef909311e1f655150f24eec27abff1376a7a8712e7962fdbb0150bfc0882078cb99e67";

$iv=pack("H*" , substr($cs_output,0,16));
$blowfish_key=pack("H*" , "0000000000000000"); // key in this example is all zero
$x =pack("H*" , substr($cs_output,16)); 
$data = mcrypt_decrypt(MCRYPT_BLOWFISH, $blowfish_key, $x , MCRYPT_MODE_CBC, $iv);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM