C#如何使用BouncyCastle创建Blowfish/ECB/NoPadding密码器
C# BouncyCastle 实现 Blowfish/ECB/NoPadding 解密方案
你调用WrapperUtilities.GetWrapper无法实现加解密是因为该方法返回的是密钥包装工具类,仅用于密钥的封装解封装,不是用于普通文本加解密的块密码实例,无法调用普通加解密的DoFinal方法。
Blowfish 的块大小为 8 字节,ECB 属于无IV的基础块工作模式,无需额外的模式封装类,NoPadding模式要求输入密文长度必须是8字节的整数倍,否则会抛出长度错误。
完整实现代码
首先引入必要的命名空间:
using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Engines; using Org.BouncyCastle.Crypto.Parameters;
解密逻辑示例:
public byte[] DecryptBlowfishEcbNoPadding(byte[] ciphertext, byte[] key) { // 1. 初始化Blowfish引擎 IBlockCipher blowfishEngine = new BlowfishEngine(); // 2. 封装为带缓存的块密码,直接对应ECB模式 BufferedBlockCipher cipher = new BufferedBlockCipher(blowfishEngine); // 3. 初始化解密模式,传入密钥参数 cipher.Init(false, new KeyParameter(key)); // 4. 分配明文缓存 byte[] plaintext = new byte[cipher.GetOutputSize(ciphertext.Length)]; // 5. 处理密文 int len = cipher.ProcessBytes(ciphertext, 0, ciphertext.Length, plaintext, 0); // 6. 完成最后一块的处理 len += cipher.DoFinal(plaintext, len); // 7. NoPadding模式下输入长度为块的整数倍,len等于plaintext长度,可直接返回,如需截断也可以返回前len位 if (len < plaintext.Length) { Array.Resize(ref plaintext, len); } return plaintext; }
注意事项
- Blowfish 合法密钥长度范围为32位到448位,即密钥字节数组长度需要在4~56之间
- NoPadding模式下密文长度必须是8的整数倍,不符合要求的密文会在调用
DoFinal时抛出异常 - 如果需要切换为加密模式,只需要将
cipher.Init的第一个参数改为true即可
内容的提问来源于stack exchange,提问作者TePi
相关产品推荐
相关产品推荐

