日期:2014-05-18  浏览次数:20743 次

帮翻译一个断代码,只剩中文处理出错
源代码ASP
VB code
Function Encrypt(PlainStr, key)
    Dim Char, KeyChar, NewStr
    Dim Pos
    Dim i , Side1 , Side2
    Pos = 1
    For i = 1 To Len(PlainStr)
        Char = Mid(PlainStr, i, 1)
        KeyChar = Mid(key, Pos, 1)
        NewStr = NewStr & Chr(Asc(Char) Xor Asc(KeyChar))
        If Pos = Len(key) Then Pos = 0
        Pos = Pos + 1
    Next 
    If Len(NewStr) Mod 2 = 0 Then
        Side1 = StrReverse(Left(NewStr, (Len(NewStr) / 2)))
        Side2 = StrReverse(Right(NewStr, (Len(NewStr) / 2)))
        NewStr = Side1 & Side2
    End If
    Encrypt = NewStr
End Function


目的代码C#
C# code

        public string Encode(string PlainStr, string Key)
        {
            string tmp = "";//结果
            char[] dChar = PlainStr.ToCharArray();
            char[] KeyChar = Key.ToCharArray();
            int Pos = 0;
            for (int i = 0; i < PlainStr.Length; i++)
            {
                char r = (char)(((int)dChar[i]) ^ ((int)KeyChar[Pos]));
                tmp += r.ToString();
                Pos++;
                if (Pos == Key.Length) { Pos = 0; }
            }
            if (tmp.Length % 2 == 0)
            {
                string Side1 = Reverse(Left(tmp, (tmp.Length / 2)));
                string Side2 = Reverse(Right(tmp, (tmp.Length / 2)));
                tmp = Side1 + Side2;
            }
            return tmp;
        }



现在C#代码可正确加密英文字符,但是中文字符加密就和ASP的有区别,问题应该在编码上,但屡试不爽。请高手赐教

------解决方案--------------------
因为string是unicode编码,所以PlainStr.Length,key.Length就要出问题了,你不如搞成byte[]数组进行加密,试试吧
------解决方案--------------------
屡试不爽的意思是用的很爽……
------解决方案--------------------
試試以下代碼
private static string Encode(string PlainStr, string Key)
{
string tmp = null;//结果
string dChar = null;
string KeyChar = null;
int Pos = 0;
for (int i = 0; i < PlainStr.Length; i++)
{
dChar = Mid(PlainStr, i, 1);
KeyChar = Mid(Key, Pos, 1);
tmp += Chr(Asc(dChar) ^ Asc(KeyChar));
Pos++;
if (Pos == Key.Length) { Pos = 0; }
}
if (tmp.Length % 2 == 0)
{
string Side1 = Reverse(Left(tmp, (tmp.Length / 2)));
string Side2 = Reverse(Right(tmp, (tmp.Length / 2)));
tmp = Side1 + Side2;
}
return tmp;
}

private static string Reverse(string str)
{
char[] arr = new char[str.Length];
for (int i = 0; i < str.Length; i++)
arr[i] = str[str.Length - 1 - i];
return new string(arr);
}

private static string Left(string str, int length)
{
return str.Substring(0, length);
}

private static string Right(string str, int length)
{
return str.Substring(str.Length - length, length);
}

private static string Mid(string str, int startIndex, int length)
{
return str.Substring(startIndex, length);
}

private static int Asc(string ch)
{
return (int)Encoding.Default.GetBytes(ch)[0];
}

private static Char Chr(int i)
{
return Convert.ToChar(i);
}