背景:我正在尝试将 Mike Shaffer 的 VB RC4 加密转换为 C# ( http://www.4guysfromrolla.com/articles/091802-1.3.aspx )。在Converting Mike Shaffer's RC4Encryption to C#中查看我的上一个问题。
看来我的加密不起作用。
使用位于http://www.4guysfromrolla.com/demos/rc4test.asp的演示页面,密码为“abc”:
纯文本:og;|Q{Fe应该导致
A2 FA E2 55 09 A4 AB 16
但是,我的代码将第 5 个字符生成为 9,而不是 09:
A2 FA E2 55 9 A4 AB 16
另一个例子 - 纯文本:cl**z!Ss应该导致
AE F1 F3 03 22 FE BE 00
但是,我的代码正在生成:
AE F1 F3 3 22 FE BE 0
似乎这只是某些非字母数字字符的问题。
这是我的代码:
private static string EnDeCrypt(string text)
{
int i = 0;
int j = 0;
string cipher = "";
// Call our method to initialize the arrays used here.
RC4Initialize(password);
// Set up a for loop. Again, we use the Length property
// of our String instead of the Len() function
for (int a = 1; a <= text.Length; a++)
{
// Initialize an integer variable we will use in this loop
int itmp = 0;
// Like the RC4Initialize method, we need to use the %
// in place of Mod
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];
// Again, since the return type of String.Substring is a
// string, we need to convert it to a char using
// String.ToCharArray() and specifying that we want the
// first value, [0].
char ctmp = text.Substring(a - 1, 1).ToCharArray()
[0];
itmp = ctmp; //there's an implicit conversion for char to int
int cipherby = itmp ^ k;
cipher += (char)cipherby; //just cast cipherby to a char
}
// Return the value of cipher as the return value of our
// method
return cipher;
}
public static string ConvertAsciiToHex(string input)
{
return string.Join(string.Empty, input.Select(c => Convert.ToInt32(c).ToString("X")).ToArray());
}
public static string Encrypt(string text)
{
return ConvertAsciiToHex(EnDeCrypt(text));
}
这是我获得加密结果的方法:
var encryptedResult = RC4Encrypt.Encrypt(valuetoencrypt);