【发布时间】:2020-03-02 19:50:38
【问题描述】:
我正在尝试使用 C# 中的 Bouncycastle 解密河豚加密字符串。
我能够轻松地加密和解密我自己的字符串,但不幸的是,我必须解密另一个系统生成的字符串。
我能够使用 C# / Bouncycastle 使用以下方法重新创建相同的字符串,但我尚未成功解密它。
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Paddings;
using Org.BouncyCastle.Crypto.Parameters;
...
static readonly Encoding Encoding = Encoding.UTF8;
public string BlowfishEncrypt(string strValue, string key)
{
try
{
BlowfishEngine engine = new BlowfishEngine();
PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(engine);
KeyParameter keyBytes = new KeyParameter(Encoding.GetBytes(key));
cipher.Init(true, keyBytes);
byte[] inB = Encoding.GetBytes(strValue);
byte[] outB = new byte[cipher.GetOutputSize(inB.Length)];
int len1 = cipher.ProcessBytes(inB, 0, inB.Length, outB, 0);
cipher.DoFinal(outB, len1);
return BitConverter.ToString(outB).Replace("-", "");
}
catch (Exception)
{
return "";
}
}
以下是我目前要解密的内容。因错误“pad block损坏”而失败的行是cipher.DoFinal(out2, len2);
public string BlowfishDecrypt(string name, string keyString)
{
BlowfishEngine engine = new BlowfishEngine();
PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(engine);
StringBuilder result = new StringBuilder();
cipher.Init(false, new KeyParameter(Encoding.GetBytes(keyString)));
byte[] out1 = Convert.FromBase64String(name);
byte[] out2 = new byte[cipher.GetOutputSize(out1.Length)];
int len2 = cipher.ProcessBytes(out1, 0, out1.Length, out2, 0);
cipher.DoFinal(out2, len2); //Pad block corrupted error happens here
String s2 = BitConverter.ToString(out2);
for (int i = 0; i < s2.Length; i++) {
char c = s2[i];
if (c != 0) {
result.Append(c.ToString());
}
}
return result.ToString();
}
知道我在 BlowfishDecrypt() 中可能做错了什么吗?
注意: 我从某处找到的 bouncycastle Java 示例转换了上述(加密和解密);加密有效。我能看到的唯一区别是 Java 示例使用了 StringBuffer,而我使用了 StringBuilder。
【问题讨论】:
-
我猜
name中的BlowfishDecrypt是来自BlowfishEncrypt的编码密文。如果是这样,您的编码不匹配。您在加密期间将密文编码为十六进制,但在解密期间尝试从 Base64 解码它。选择一种编码并坚持下去。 -
是的,对不起。 “名称”的一个示例是 BlowfishEncrypt() 的结果。你说的有道理,但我不完全确定如何解决它。我将
byte[] out1 = Convert.FromBase64String(name);更改为byte[] out1 = Encoding.GetBytes(name);但得到了同样的错误。 -
这是漫长的一天......显然应该是
Hex.Decode(name)。感谢您的帮助! -
Blowfish 真的不应该在新代码中使用,即使作者现在使用 AES。
-
“很遗憾,我必须解密另一个系统生成的字符串”
标签: c# encryption bouncycastle