在C#中使用Bouncy Castle RC4算法解密字符串

时间:2020-12-31 18:33:47

I am trying to use library Bouncy Castle for decrypting. But the decrypted string is not correct. I am getting value Aa1ŽYY445Ló, but correct value should be Aa11YY445LL. What I am doing wrong? When I try to decrypt string on http://rc4.online-domain-tools.com/ I am getting correct result.

我正在尝试使用库Bouncy Castle进行解密。但解密的字符串不正确。我得到的值是Aa1ŽYY445Ló,但正确的值应该是Aa11YY445LL。我做错了什么?当我尝试解密http://rc4.online-domain-tools.com/上的字符串时,我得到了正确的结果。

Code sample:

代码示例:

string textToDecrypt = HexDumper.FromHex("E5497380DC724B28284D80");
var key = Encoding.UTF8.GetBytes("heslo");
var cipher = new RC4Engine();
cipher.Init(true, new KeyParameter(key));

byte[] inBytes = UTF8Encoding.GetEncoding(1252).GetBytes(textToDecrypt);
byte[] outBuffer = new byte[1024 * 4];
cipher.ProcessBytes(inBytes, 0, inBytes.Length, outBuffer, 0);

// Output must be 41 61 31 31 59 59 34 34 35 4c 4c -> Aa11YY445LL
var textDecrypted = ASCIIEncoding.GetEncoding(1252).GetString(outBuffer);
int indexOf0 = textDecrypted.IndexOf("\0");
if (indexOf0 > 0)
{
    textDecrypted = textDecrypted.Substring(0, indexOf0);
    MessageBox.Show(textDecrypted);
}

public static string FromHex(string hexString)
{
    string StrValue = "";
    while (hexString.Length > 0)
    {
        StrValue += System.Convert.ToChar(System.Convert.ToUInt32(hexString.Substring(0, 2), 16)).ToString();
        hexString = hexString.Substring(2, hexString.Length - 2);
    }
    return StrValue;
}

1 个解决方案

#1


2  

The problem is your FromHex function.

问题是你的FromHex功能。

Swapped it with the top answer from How can I convert a hex string to a byte array? and got the correct result.

用顶部答案交换它如何将十六进制字符串转换为字节数组?并得到了正确的结果。

Not sure specifically what's wrong (in terms of functionality) with your FromHex, though -- you should probably figure that out.

但是不确定具体与你的FromHex有什么不对(在功能方面) - 你应该明白这一点。

#1


2  

The problem is your FromHex function.

问题是你的FromHex功能。

Swapped it with the top answer from How can I convert a hex string to a byte array? and got the correct result.

用顶部答案交换它如何将十六进制字符串转换为字节数组?并得到了正确的结果。

Not sure specifically what's wrong (in terms of functionality) with your FromHex, though -- you should probably figure that out.

但是不确定具体与你的FromHex有什么不对(在功能方面) - 你应该明白这一点。