Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from Crypto.Cipher import AES
- from Crypto.Random import get_random_bytes
- def zero_padding(data: bytes, block_size: int) -> bytes:
- padding_length = block_size - (len(data) % block_size)
- return data + b'\x00' * (padding_length % block_size)
- class NonPaddingCipher:
- def __init__(self, key: bytes):
- assert len(key) in AES.key_size
- self.k = key
- def encrypt(self, message: bytes) -> bytes:
- # padding
- plain = zero_padding(message, AES.block_size)
- # encrypt using raw AES-CBC
- iv = get_random_bytes(AES.block_size)
- aes = AES.new(self.k, AES.MODE_CBC, IV=iv)
- ciphertext = aes.encrypt(plain)
- cip = iv + ciphertext
- # reorder the ciphertext blocks
- reorder = cip[:-2*AES.block_size] + cip[-AES.block_size:] + \
- cip[-2*AES.block_size:]
- return reorder[:AES.block_size + len(message)]
- def decrypt(self, ciphertext: bytes) -> bytes:
- assert len(ciphertext) > AES.block_size
- # padding the cipherext
- cipher = zero_padding(ciphertext, AES.block_size)
- # extract the last two blocks of ciphertext
- c_k = cipher[-2*AES.block_size:-AES.block_size] # C_{k}
- c_kp1 = cipher[-AES.block_size:] # C'_{k+1}
- # calculate B'_{k+1} = F^{-1}_k(IV=C'_{k+1} || C_{k})
- aes = AES.new(self.k, AES.MODE_CBC, IV=c_kp1)
- b_kp1 = aes.decrypt(c_k)
- # calculate l
- last_block_size = len(ciphertext) % AES.block_size
- if last_block_size == 0:
- last_block_size = AES.block_size
- # C'_k = C_{k+1} + B'_k+1
- c_k_real = c_kp1[:last_block_size] + b_kp1[last_block_size:]
- # restore the original ciphertext
- cip = cipher[:-2*AES.block_size] + c_k_real + c_k
- # decrypt using raw AES-CBC
- iv = cip[:AES.block_size]
- aes = AES.new(self.k, AES.MODE_CBC, IV=iv)
- plain = aes.decrypt(cip[AES.block_size:])
- # check the padding
- if last_block_size < AES.block_size:
- if any(plain[-AES.block_size:][last_block_size:]):
- print("Bad Padding")
- return None
- return plain[:len(ciphertext) - AES.block_size]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement