X-Git-Url: https://code.kerkeslager.com/?p=sandbox;a=blobdiff_plain;f=cryptopals-python%2Fcryptopals.py;h=24392b8f4d0ecdbe277490b23be466d269f90481;hp=ee811128e6851f30fcd17c4ac552ca4703851ade;hb=HEAD;hpb=45ec9c36ab7241cee93e615b3c901b5b80aa7aff diff --git a/cryptopals-python/cryptopals.py b/cryptopals-python/cryptopals.py index ee81112..24392b8 100644 --- a/cryptopals-python/cryptopals.py +++ b/cryptopals-python/cryptopals.py @@ -41,6 +41,19 @@ def encrypt_with_repeating_xor(plaintext, key): (key_bytes * ((len(plaintext_bytes) // len(key_bytes)) + 1))[:len(plaintext_bytes)], ) +def hamming_weight(_bytes): + def hamming_weight_of_byte(b): + count = 0 + while b > 0: + count += 1 + b &= b - 1 + return count + + return sum(hamming_weight_of_byte(b) for b in _bytes) + +def hamming_distance(bytes0, bytes1): + return hamming_weight(xor_bytes(bytes0, bytes1)) + class Set1Challenge1Tests(unittest.TestCase): def test_converts_hex_to_base64(self): expected = 'SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t\n' @@ -127,5 +140,19 @@ class Set1Challenge5Tests(unittest.TestCase): self.assertEqual(expected, actual) +with open('set1challenge6.txt','r') as f: + set1challenge6text = f.read() + +class Set1Challenge6Tests(unittest.TestCase): + def test_hamming_distance(self): + expected = 37 + actual = hamming_distance(b'this is a test', b'wokka wokka!!!') + self.assertEqual(expected, actual) + + def test_find_repeated_xor_keysize(self): + expected = 0 + actual = find_repeated_xor_keysize(set1challenge6text) + self.assertEqual(expected, actual) + if __name__ == '__main__': unittest.main()