user1357872
user1357872

Reputation: 803

operator 'xor' is not defined for types 'char' and 'integer' in xorencryption?

Given below is program for encrypting a string. I had taken this code from the below link and converted to vb.net. http://www.eggheadcafe.com/tutorials/csharp/8b53894c-a889-4914-8c46-122980cc44ae/simple-xor-encryption.aspx. This will convert string using simple xor encryption.

Namespace SimpleXOREncryption
    Public NotInheritable Class EncryptorDecryptor
        Private Sub New()
        End Sub
        Public Shared key As Integer = 129

        Public Shared Function EncryptDecrypt(ByVal textToEncrypt As String) As String
            Dim inSb As New StringBuilder(textToEncrypt)
            Dim outSb As New StringBuilder(textToEncrypt.Length)
            Dim c As Char
            For i As Integer = 0 To textToEncrypt.Length - 1
                c = inSb(i)
                c = ChrW(c Xor key)
                outSb.Append(c)
            Next
            Return outSb.ToString()
        End Function
    End Class
End Namespace

Im getting error

"operator 'xor' is not defined for types 'char' and 'integer'"

where i made mistake?

Upvotes: 0

Views: 1999

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1502006

Basically, VB doesn't allow Xor between Char and Integer, as the compiler is telling you. The C# compiler is automatically promoting char to int, but the VB compiler doesn't do this (at least in this case). You need to convert the character to an integer explicitly first:

c = ChrW(AscW(c) Xor key)

I would strongly advise you not to use this "encryption" (aka obfuscation) for any production project though. .NET comes with plenty of encryption algorithms built in - why not use one of those? Heed the warning about the above approach also not always giving valid XML characters, too. Heck, it could yield strings which are basically invalid due to containing "halves" of surrogate pairs etc. You should be nervous of anything which treats character data as arbitrary numbers.

Upvotes: 4

Related Questions