使用带有Coldfusion和.NET / BouncyCastle的Blowfish加密和解密数据

时间:2019-01-24 18:08:38

标签: c# encryption coldfusion bouncycastle blowfish

我正在尝试使用BouncyCastle for ASP.NET MVC模仿Coldfusion Blowfish / Hex加密。我能够使用此链接中列出的步骤成功解密以CF加密的字符串:Encrypt and Decrypt data using Blowfish/CBC/PKCS5Padding

除了在7个字符串的末尾添加\ 0之外,它都很好用。

我不是在尝试使用Blowfish / CBC / PKCS5Padding,而只是在使用Blowfish / Hex。我无法进行反向(加密)工作。下面是我到目前为止的代码

我尝试使用=的手动填充,以及忽略。但是,即使使用附加字符,它仍然不会同步。

解密(可以):

string keyString = "TEST";
BlowfishEngine engine = new BlowfishEngine();
PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(engine);
cipher.Init(false, new KeyParameter(Convert.FromBase64String(keyString)));
byte[] out1 = Hex.Decode(hexstring);
byte[] out2 = new byte[cipher.GetOutputSize(out1.Length)];
int len2 = cipher.ProcessBytes(out1, 0, out1.Length, out2, 0);
cipher.DoFinal(out2, len2);
string myval = Encoding.UTF8.GetString(out2);

加密(无效):

string keyString = "TEST";
string stringToEncrypt = "0123456";
stringToEncrypt = stringToEncrypt + "=";
BlowfishEngine engine2 = new BlowfishEngine();
PaddedBufferedBlockCipher cipher2 = new PaddedBufferedBlockCipher(engine2);
cipher2.Init(true, new KeyParameter(Convert.FromBase64String(keyString)));
byte[] inB = Hex.Encode(Convert.FromBase64String(stringToEncrypt));
byte[] outB = new byte[cipher2.GetOutputSize(inB.Length)];
int len1 = cipher2.ProcessBytes(inB, 0, inB.Length, outB, 0);
cipher2.DoFinal(outB, len1);
var myval2 = BitConverter.ToString(outB).Replace("-", "");

“无效”的含义-它返回一个加密的字符串,该字符串绝不镜像CF加密的字符串。最重要的是,使用上述方法解密后,返回的字符串与最初输入的字符串(使用.NET / BouncyCastle加密)不匹配

1 个答案:

答案 0 :(得分:1)

当C#代码实际上只是纯文本时,它会将输入解码为base64。因此,您正在加密错误的值。这就是为什么结果与CF中的加密字符串不匹配的原因。由于CF始终使用UTF8,请使用以下命令:

byte[] inB = Encoding.UTF8.GetBytes(stringToEncrypt);

代替:

byte[] inB = Hex.Encode(Convert.FromBase64String(stringToEncrypt));

其他安全提示:

  1. 我不是加密专家,但是from what I've read您应该使用CBC模式,每次都使用不同的IV,以提高安全性。 (当前代码使用的是ECB,这不太安全。)

  2. 对于以后阅读此线程的任何人来说,键值“ TEST”显然仅用于说明。 请勿将任意值用作键,因为它会削弱安全性。始终使用标准加密库生成的强密钥。例如,在CF中,使用GenerateSecretKey函数。

相关问题