我正在关注一篇文章,http://www.4guysfromrolla.com/articles/091802-1.3.aspx,它展示了如何将 Mike Shaffer 的 VB RC4 加密转换为 C#,但是我得到的结果与原始文章不同,http://www.4guysfromrolla.com/webtech/010100-1.shtml。
使用原始文章中的此测试链接http://www.4guysfromrolla.com/demos/rc4test.htm,密码为“abc”,纯文本为“testing123”,我得到“B9 F8 AA 5D 31 B1 8A 42 1E D4"。然而,当使用 C# 版本时,我得到了一些稍微不同的东西:“b9 f8 aa 5d 31 b1 160 42 1e d4”。我得到“160”而不是“8A”。
这是我将 ASCII(C# 方法的最终结果)转换为十六进制的方法:
public static string ConvertAsciiToHex(string input)
{
return string.Join(string.Empty, input.Select(c => Convert.ToInt32(c).ToString("X")).ToArray());
}
这是我从文章中获得的 C# 代码(修改为静态类):
protected static int[] sbox = new int[256];
protected static int[] key = new int[256];
private static string password = "abc";
private static void RC4Initialize(string strPwd)
{
int intLength = strPwd.Length;
for (int a = 0; a <= 255; a++)
{
char ctmp = (strPwd.Substring((a % intLength), 1).ToCharArray()[0]);
key[a] = Microsoft.VisualBasic.Strings.Asc(ctmp);
sbox[a] = a;
}
int x = 0;
for (int b = 0; b <= 255; b++)
{
x = (x + sbox[b] + key[b]) % 256;
int tempSwap = sbox[b];
sbox[b] = sbox[x];
sbox[x] = tempSwap;
}
}
private static string EnDeCrypt(string text)
{
int i = 0;
int j = 0;
string cipher = "";
RC4Initialize(password);
for (int a = 1; a <= text.Length; a++)
{
int itmp = 0;
i = (i + 1) % 256;
j = (j + sbox[i]) % 256;
itmp = sbox[i];
sbox[i] = sbox[j];
sbox[j] = itmp;
int k = sbox[(sbox[i] + sbox[j]) % 256];
char ctmp = text.Substring(a - 1, 1).ToCharArray()
[0];
itmp = Microsoft.VisualBasic.Strings.Asc(ctmp);
int cipherby = itmp ^ k;
cipher += Microsoft.VisualBasic.Strings.Chr(cipherby);
}
return cipher;
}
我这样调用方法:
public static string Encrypt(string text)
{
return ConvertAsciiToHex(EnDeCrypt(text));
}
RC4Encrypt.Encrypt("testing123");
我究竟做错了什么?