# Artificial truth

## The more you see, the less you believe.

[archives] [latest] | [homepage] | [atom/rss]

# Elegant xor encryption in Python Thu 20 December 2012 — download

Python doesn't support (natively) XOR on everything else than int, and this is annoying.

```>>> 'hello' ^ 'world'
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: unsupported operand type(s) for ^: 'str' and 'str'
```

# Solution

Fortunately, Python has the (amazing) itertools module:

```# Stupid XOR demo
from itertools import cycle, izip

message = 'attack at dawn'
key = 's3cr3t'

cyphered = ''.join(chr(ord(c)^ord(k)) for c,k in izip(message, cycle(key)))
print('%s ^ %s = %s' % (message, key, cyphered))
message = ''.join(chr(ord(c)^ord(k)) for c,k in izip(cyphered, cycle(key)))
print('%s ^ %s = %s' % (cyphered, key, message))
```

This prints:

```\$ python xor.py
attack at dawn ^ s3cr3t = GPSRRW]
GPSRRW] ^ s3cr3t = attack at dawn
```

# Explanations

For those who are not familiar with python:

• `cycle(key)` returns an iterator that produces an infinite concatenation of key's content
• `izip(a, b)` returns an iterator that aggregates elements from each of the iterables. It stops on the shortest input sequence (here, our message, since cycle(key) is infinite
• `ord(a)`and `chr(57)` return (respectively) the integer representing the given char and the char represented by the given integer.
• `'.join()` (roughly) concatenate every items of the list passed in argument in a string

Yes, Python is amazing.