-1

我正在学习如何使用 BouncyCastle c# 密码库进行加密。我不打算发送消息,所以我不考虑安全性等。我已经在 Visual Studio 中编写了我的 c# 代码。

这是问题所在。我在 CFB 模式下使用 Twofish加密了文本“ Hello World! ”。关键是1234567812345678。我用过phpfiddle http://phpfiddle.org/在线工具。

$algo = 'twofish';
$mode = 'cfb';

$cipher = mcrypt_module_open($algo,'',$mode,'');

$key = hex2bin('31323334353637383132333435363738'); //1234567812345678
$iv = hex2bin('00000000000000000000000000000000');

mcrypt_generic_init($cipher, $key, $iv);

$plaintext = utf8_encode('Hello World!');
$encrypted = mcrypt_encrypt($algo, $key, $plaintext, $mode, $iv);
printf("<br>Encrypted text: %s<br><br>",base64_encode($encrypted));

$decrypted = mcrypt_decrypt($algo, $key, $encrypted, $mode, $iv);
printf("<br>Decrypted text: %s (%s)<br><br>",$decrypted,bin2hex($decrypted));

mcrypt_generic_deinit($cipher);
mcrypt_module_close($cipher);

结果如下

cfdJ+M6MAzG4WJMb (Base64)

然后我创建了 ac# 版本来解密相同的文本

// ASCII encoding and Zero padding
encoding = Encoding.ASCII
padding = IBlockCipherPadding.zeroBytePadding

// Set up the engine and cipher types
baseCipher = new TwofishEngine();
blockSize = baseCipher.GetBlockSize();    

modeCipher = new CfbBlockCipher(baseCipher, blockSize);
cipher = padding == null ? new PaddedBufferedBlockCipher(modeCipher) : new PaddedBufferedBlockCipher(modeCipher, padding);

// convert the strings to byte array and create a dummy 000000.. iv 

byte[] iv = new byte[blockSize];    // i.e. 16 bytes of zero
keyBytes = _encoding.GetBytes(key);   //1234567812345678
inputBytes = Convert.FromBase64String(inp);

// initiate the cipher with iv parameters
cipher.Init(true, new ParametersWithIV(new KeyParameter(keyBytes), iv));

// do the decryption
console.write(_encoding.GetString(cipher.DoFinal(inputBytes)) + "\n";)

但这给了我垃圾。我得到 HIl1oVW�rEdIp�</p>

关闭 (HloWrd) 但其他所有字母都是错误的!

ECB 模式工作正常,因此它必须与初始化向量有关。

PHP 和 c# 之间是否有一些我还没有学过的区别?

在这种情况下,我的 c# 代码在哪里不正确?

4

1 回答 1

0

好的。所以我终于解决了。我对密码块模式的理解中的一个基本错误。CFB 和 OFB 是流密码而不是填充缓冲块密码。

因此密码设置应该是

modeCipher = new CfbBlockCipher(baseCipher,8);      // Allways 8 bits for a stream cipher !!
cipher = new StreamBlockCipher(modeCipher);

(cipher.doFinal 也已更改,但此处未显示)

它现在工作正常。

于 2016-02-04T23:13:04.990 回答