Title: Elegant xor encryption in Python
Date: 2012-12-20 23:40

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

```lisp
>>> '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]( http://docs.python.org/2/library/itertools.html ) module:

```python
# 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:

```bash
$ 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.
