繁体   English   中英

RC4加密非字母数字错误

[英]RC4 Encryption non-alphanumeric wrong

背景:我正在尝试将Mike Shaffer的VB RC4加密转换为C#( http://www.4guysfromrolla.com/articles/091802-1.3.aspx )。 将Mike Shaffer的RC4Encryption转换为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 cryptoResult = RC4Encrypt.Encrypt(valuetoencrypt);

输出是正确的(前导零不会改变值),您的代码只是没有填充适合单个十六进制数字(例如9或3或0)的值。 使用.ToString("X2")代替.ToString("X")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM