Python byte per byte XOR decryption

Posted by neurino on Stack Overflow See other posts from Stack Overflow or by neurino
Published on 2010-05-10T20:59:41Z Indexed on 2010/05/10 21:04 UTC
Read the original article Hit count: 359

Filed under:
|
|
|

I have an XOR encypted file by a VB.net program using this function to scramble:

Public Class Crypter
    ...
    'This Will convert String to bytes, then call the other function.
    Public Function Crypt(ByVal Data As String) As String
        Return Encoding.Default.GetString(Crypt(Encoding.Default.GetBytes(Data)))
    End Function

    'This calls XorCrypt giving Key converted to bytes
    Public Function Crypt(ByVal Data() As Byte) As Byte()
        Return XorCrypt(Data, Encoding.Default.GetBytes(Me.Key))
    End Function

    'Xor Encryption.
    Private Function XorCrypt(ByVal Data() As Byte, ByVal Key() As Byte) As Byte()
        Dim i As Integer
        If Key.Length <> 0 Then
            For i = 0 To Data.Length - 1
                Data(i) = Data(i) Xor Key(i Mod Key.Length)
            Next
        End If
        Return Data
    End Function
End Class

and saved this way:

Dim Crypter As New Cryptic(Key)
'open destination file
Dim objWriter As New StreamWriter(fileName)
'write crypted content
objWriter.Write(Crypter.Crypt(data))

Now I have to reopen the file with Python but I have troubles getting single bytes, this is the XOR function in python:

def crypto(self, data):
    'crypto(self, data) -> str'
    return ''.join(chr((ord(x) ^ ord(y)) % 256) \
        for (x, y) in izip(data.decode('utf-8'), cycle(self.key))

I had to add the % 256 since sometimes x is > 256 i.e. not a single byte.

This thing of two bytes being passed does not break the decryption because the key keeps "paired" with the following data.

The problem is some decrypted character in the conversion is wrong. These chars are all accented letters like à, è, ì but just a few of the overall accented letters. The others are all correctly restored.

I guess it could be due to the 256 mod but without it I of course get a chr exception...

Thanks for your support

© Stack Overflow or respective owner

Related posts about python

Related posts about xor