C#和VB中的简单加密会返回不同的结果

时间:2011-12-09 13:43:54

标签: c# vb.net encryption password-encryption

我有一个应用程序,用于加密用VB编写的数据。还有另一个使用相同数据的应用程序。加密代码相同但在某些情况下会返回不同的结果。以下是VB和C#中的加密代码。

=================================== VB CODE ========== =======================

Dim s1 As String = ""
Dim i As Integer

If value = 0 Then value = 52

For i = 0 To s.Length - 1
   s1 += Chr(Asc(s.Substring(i, 1)) Xor value)
Next

Return s1

=================================== C#CODE ========== =======================

string Result = ""; 

int i = 0;

   try
   {
    if (value == 0)
        value = 52;

    char[] chars = s.ToCharArray();

    for (i = 0; i <= chars.Length - 1; i++)
    {
        Result += (char)((int)(chars[i]) ^ value);
    }


}
catch (Exception ex)
{
    MessageBox.Show(ex.Message, "Error");
}

return Result;

3 个答案:

答案 0 :(得分:4)

VB.NET Chr()和Asc()函数是遗留函数,它们与早期版本的Visual Basic处理字符的方式兼容。他们假设系统代码页中有8位编码。请改用Unicode兼容的ChrW()和AscW()函数。或者如果需要C#代码来生成与VB.NET代码相同的结果,请使用Encoding.Default.GetBytes()。

答案 1 :(得分:0)

试试这个VB代码:

Dim Result As String = ""

Dim i As Integer = 0

Try
    If value = 0 Then
        value = 52
    End If

    Dim chars As Char() = s.ToCharArray()

    For i = 0 To chars.Length - 1
        Result += CChar(CInt(chars(i)) Xor value)


    Next
Catch ex As Exception
    MessageBox.Show(ex.Message, "Error")
End Try

Return Result

答案 2 :(得分:0)

在投射时尝试使用(byte)或(short)代替(int)。这可能有用!