为 c# bouncycastle 编写 php MCrypt twofish

writing php MCrypt twofish for c# bouncycastle

我正在学习如何使用 BouncyCastle c# 密码库进行加密。我不想发送消息,所以我没有考虑安全性等问题。 我已经在 Visual Studio.

中编写了我的 C# 代码

问题来了。我在 CFB 模式下使用 Twofish 加密了文本“Hello World!”。密钥是1234567812345678。我用过phpfiddlehttp://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)

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

// 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�

接近(H.l.o.W.r.d.)但每隔一个字母都是错误的!

ECB 模式工作正常,所以它一定与初始化向量有关。

PHP 和 c# 之间有什么我还没有学过的区别吗?

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

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

因此密码设置应该是

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

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

现在可以正常使用了。