我试图用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块损坏"是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。
答案 0 :(得分:0)
谢谢你,Artjom B!
byte[] out1 = Convert.FromBase64String(name);
应该是
byte[] out1 = Hex.Decode(name);
从那里,我所要做的就是将Hex转换为字符串。