1

私は記事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」という少し異なる結果が得られます。「8A」ではなく「160」になっています。

ASCII(C#メソッドの最終結果)を16進数に変換する私のメソッドは次のとおりです。

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");

私は何を間違っていますか?

4

1 に答える 1

1

Chrとの呼び出しの違いChrWです。

Chr0 から 255 までの値のみを取り、値がその範囲外の char を返します (少なくとも以下に示すように、私のマシンでは)。あなたは138を見ていました。

128 != 8364 (?)
130 != 8218 (,)
131 != 402 (ƒ)
132 != 8222 (,)
133 != 8230 (.)
134 != 8224 (+)
135 != 8225 (╪)
136!=710(^)
137 != 8240 (%)
138 != 352 (小)
139 != 8249 ()
156 != 339 (お)
158 != 382 (ズ)
159 != 376 (Y)

より良い説明のために、VB.Net開発者が必要になるかもしれません... ;-)


ただし、Microsoft.VisualBasic呼び出しを使用する必要はほとんどありません (VB を呼び出すときの翻訳はほとんどありません... ;-) ) char

itmp = ctmp;  //there's an implicit conversion for char to int

int cipherby = itmp ^ k;

Console.WriteLine("cipherby = {0}", cipherby);
cipher += (char)cipherby; //just cast cipherby to a char
于 2013-07-09T21:29:28.747 に答える