Skip to content

Instantly share code, notes, and snippets.

@cameronp98
Last active January 2, 2016 18:19
Show Gist options
  • Save cameronp98/8342733 to your computer and use it in GitHub Desktop.
Save cameronp98/8342733 to your computer and use it in GitHub Desktop.
import unittest
from itertools import cycle
from binascii import hexlify
from os import urandom
# returns a random hex string of length l
# urandom returns 2 bits for every length unit hence the 'l/2'
uniqid = lambda l: hexlify(urandom(round(l/2))).decode()
# '^' = xor (exclusive or): is true when bit a != bit b e.g. 0b10 ^ 0b01 = 0b11
xor = lambda s, k: "".join(chr(ord(x) ^ ord(y)) for x,y in zip(s, cycle(k)))
class TestXOR(unittest.TestCase):
def setUp(self):
self.string = "This needs to be encrypted"
self.key = uniqid(16)
def test_decryption(self):
""" Test that the decrypted string == the original string"""
encrypted = xor(self.string, self.key)
self.assertEqual(self.string, xor(encrypted, self.key))
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment