2016-09-16 15:04:46 +03:00
|
|
|
import os
|
2016-09-03 21:34:24 +03:00
|
|
|
import pyaes
|
|
|
|
|
|
|
|
|
|
|
|
class AES:
|
|
|
|
@staticmethod
|
|
|
|
def decrypt_ige(cipher_text, key, iv):
|
2016-09-04 12:07:18 +03:00
|
|
|
"""Decrypts the given text in 16-bytes blocks by using the given key and 32-bytes initialization vector"""
|
2016-11-30 00:29:42 +03:00
|
|
|
iv1 = iv[:len(iv) // 2]
|
|
|
|
iv2 = iv[len(iv) // 2:]
|
2016-09-03 21:34:24 +03:00
|
|
|
|
|
|
|
aes = pyaes.AES(key)
|
|
|
|
|
2016-09-16 15:04:46 +03:00
|
|
|
plain_text = []
|
2016-09-03 21:34:24 +03:00
|
|
|
blocks_count = len(cipher_text) // 16
|
|
|
|
|
|
|
|
cipher_text_block = [0] * 16
|
|
|
|
for block_index in range(blocks_count):
|
|
|
|
for i in range(16):
|
2016-11-30 00:29:42 +03:00
|
|
|
cipher_text_block[i] = cipher_text[block_index * 16 + i] ^ iv2[
|
|
|
|
i]
|
2016-09-03 21:34:24 +03:00
|
|
|
|
|
|
|
plain_text_block = aes.decrypt(cipher_text_block)
|
|
|
|
|
|
|
|
for i in range(16):
|
|
|
|
plain_text_block[i] ^= iv1[i]
|
|
|
|
|
|
|
|
iv1 = cipher_text[block_index * 16:block_index * 16 + 16]
|
2016-09-16 15:04:46 +03:00
|
|
|
iv2 = plain_text_block[:]
|
2016-09-03 21:34:24 +03:00
|
|
|
|
2016-09-16 15:04:46 +03:00
|
|
|
plain_text.extend(plain_text_block[:])
|
2016-09-03 21:34:24 +03:00
|
|
|
|
|
|
|
return bytes(plain_text)
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def encrypt_ige(plain_text, key, iv):
|
2016-09-04 12:07:18 +03:00
|
|
|
"""Encrypts the given text in 16-bytes blocks by using the given key and 32-bytes initialization vector"""
|
2016-09-16 15:04:46 +03:00
|
|
|
|
|
|
|
# Add random padding if and only if it's not evenly divisible by 16 already
|
|
|
|
if len(plain_text) % 16 != 0:
|
|
|
|
padding_count = 16 - len(plain_text) % 16
|
|
|
|
plain_text += os.urandom(padding_count)
|
2016-09-03 21:34:24 +03:00
|
|
|
|
2016-11-30 00:29:42 +03:00
|
|
|
iv1 = iv[:len(iv) // 2]
|
|
|
|
iv2 = iv[len(iv) // 2:]
|
2016-09-03 21:34:24 +03:00
|
|
|
|
|
|
|
aes = pyaes.AES(key)
|
|
|
|
|
2016-09-16 15:04:46 +03:00
|
|
|
cipher_text = []
|
2016-09-03 21:34:24 +03:00
|
|
|
blocks_count = len(plain_text) // 16
|
|
|
|
|
|
|
|
for block_index in range(blocks_count):
|
2016-11-30 00:29:42 +03:00
|
|
|
plain_text_block = list(plain_text[block_index * 16:block_index *
|
|
|
|
16 + 16])
|
2016-09-03 21:34:24 +03:00
|
|
|
for i in range(16):
|
|
|
|
plain_text_block[i] ^= iv1[i]
|
|
|
|
|
|
|
|
cipher_text_block = aes.encrypt(plain_text_block)
|
|
|
|
|
|
|
|
for i in range(16):
|
|
|
|
cipher_text_block[i] ^= iv2[i]
|
|
|
|
|
2016-09-16 15:04:46 +03:00
|
|
|
iv1 = cipher_text_block[:]
|
2016-09-03 21:34:24 +03:00
|
|
|
iv2 = plain_text[block_index * 16:block_index * 16 + 16]
|
|
|
|
|
2016-09-16 15:04:46 +03:00
|
|
|
cipher_text.extend(cipher_text_block[:])
|
2016-09-03 21:34:24 +03:00
|
|
|
|
|
|
|
return bytes(cipher_text)
|