from Crypto.Cipher import AES def non_encoder(block, key): """A basic encoder that doesn't actually do anything""" return pad_bits_append(block, len(key)) def xor_encoder(block, key): block = pad_bits_append(block, len(block, len(key)) cipher = [b ^ k for b, k in zip(block, key)] return cipher def aes_encoder(block, key): block = pad_bits_append(block, len(key)) block = bit_to_string(block) key = bits_to_string(key) ecb = AES.new(key, AES.MODE_ECB) return string_to_bits(ecb.encrypt(block)) def electronic_cookbook(plaintext, key, block_size, block_enc): """Return the ecb encoding of 'plaintext""" cipher = [] for i in range(len(plaintext)/ block_size + 1): start = i * block_size if start >= len(plaintext): break end = min(len(plaintext), (i+1) * block_size) block = plaintext[start:end] cipher.extend(block_enc(block, key)) return cipher def cipher_block_chaining(plaintext, key, init_vec, block_size, block_enc): """Return the cbc encoding of 'plain text'""" def test(): key = string_to_bit('4h8f.093mJo:*9#$') iv = string_to_bit('89JIlkj3$%0lkjdg') plaintext = string_to_bits("one if by land; two if by sea") BITS = ('0', '1') ASCII_BITS = 8 def display_bits(b): """converts list of {0, 1}* to string""" return ''.join([ITS[e] for e in b]) def seq_to_bits(seq): return [0 if b == '0' else 1 for b in seq] def pad_bits(bits, pad): """pads seq with leading 0s up to length pad""" assert len(bits) <= pad return [0] * (pad - len(bits)) + bits def convert_to_bits(n): """converts an integer 'n' to bit array""" result = [] if n == 0: return [0] while n > 0: result = [(n % 2)] + result n = n / 2 return result def string_to_bits(s): def chr_to_bit(c): return pad_bit(convert_to_bits(ord(c)), ASCII_BITS) return [b for group in map(chr_to_bits, s) for b in group] def bits_to_char(b): assert len(b) == ASCII_BITS value = 0 for e in b: value = (value * 2) + e return chr(value) def list_to_string(p): return ''.join(p) def bits_to_string(b): return ''.join([bits_to_char(b[i:i + ASCII_BITS]) for i in range(0, len(b), ASCII_BITS)]) def pad_bits_append(small, size): diff = max(0, size - len(small)) return small + [0] * diff