简体   繁体   中英

simple encryption in C# and VB returns different results

I have an application that encrypts data which is written in VB. There is another application that uses the same data. Encryption code is the same but it returns different result in some cases. Below are the encryption code in VB and 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;

The VB.NET Chr() and Asc() functions are legacy functions that are compatible with the way early versions of Visual Basic treated characters. They assume 8-bit encoding in the system code page. Use the Unicode compatible ChrW() and AscW() functions instead. Or use Encoding.Default.GetBytes() if you need the C# code to produce the same result as the VB.NET code.

Try using (byte) or (short) instead of (int) when you cast it. That may work!

Try this VB Code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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