import unittest
def base64_from_hex(_hex):
- return codecs.encode(codecs.decode(_hex, 'hex'), 'base64').decode('utf-8')
+ return codecs.encode(bytes.fromhex(_hex), 'base64').decode('utf-8')
+
+def hex_xor(hex0, hex1):
+ assert len(hex0) == len(hex1)
+ bytes0 = bytes.fromhex(hex0)
+ bytes1 = bytes.fromhex(hex1)
+ xored_bytes = bytes(byte0 ^ byte1 for byte0, byte1 in zip(bytes0, bytes1))
+ return codecs.encode(xored_bytes, 'hex').decode('utf-8')
class Set1Challenge1Tests(unittest.TestCase):
def test_converts_hex_to_base64(self):
actual = base64_from_hex('49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d')
self.assertEqual(expected, actual)
+class Set1Challenge2Tests(unittest.TestCase):
+ def test_xors_hex_strings(self):
+ hex0 = '1c0111001f010100061a024b53535009181c'
+ hex1 = '686974207468652062756c6c277320657965'
+
+ expected = '746865206b696420646f6e277420706c6179'
+ actual = hex_xor(hex0, hex1)
+
+ self.assertEqual(expected, actual)
+
if __name__ == '__main__':
unittest.main()