def test_decrypt_bytes_not_padded_raises(self): b = b"\x00\x01\x00\x01\x23" iv = b"\x03\x03" cbc = CBCMode( blksize=2, encrypt_blk=self.mock_fun, decrypt_blk=self.mock_fun, iv=iv, ) with self.assertRaises(ValueError): cbc.decrypt(b)
def is_admin(encrypted: bytes, blksize: int = 16) -> bool: """ params: encrypted: message encrypted using `encryption_oracle()` blksize: blocksize used by `encryption_oracle()` returns: True if decrypted message contains ";admin=true;", False otherwise """ cipher = AES.new(CONSISTENT_KEY, AES.MODE_ECB) cbc = CBCMode(blksize=blksize, encrypt_blk=cipher.encrypt, decrypt_blk=cipher.decrypt, iv=CONSISTENT_IV) padded = cbc.decrypt(encrypted) decrypted = PKCS7Padding.unapply(padded) return b";admin=true;" in decrypted
def test_encrypt_decrypt_integration_case(self): key = b"YELLOW SUBMARINE" iv = b"THIS IS 16 BYTES" cipher = AES.new(key, AES.MODE_ECB) cbc = CBCMode( blksize=16, encrypt_blk=cipher.encrypt, decrypt_blk=cipher.decrypt, iv=iv, ) plaintext = (b"Lorem ipsum dolo" b"r sit amet, cons" b"ectetur adipisci" b"ng elitAAAAAAAAA") encrypted = cbc.encrypt(plaintext) decrypted = cbc.decrypt(encrypted) self.assertEqual(plaintext, decrypted)
def validate_ascii(encrypted: bytes) -> bytes: """ params: encrypted: message encrypted using `aes_cbc()` returns: decrypted bytes if they contain extended ascii characters, None otherwise """ cipher = AES.new(key, AES.MODE_ECB) cbc = CBCMode(blksize=blksize, encrypt_blk=cipher.encrypt, decrypt_blk=cipher.decrypt, iv=key) padded = cbc.decrypt(encrypted) decrypted = PKCS7Padding.unapply(padded) for c in decrypted: if c >= 128: return decrypted return None
def valid_padding(encrypted: bytes, iv: bytes) -> bool: """ params: encrypted: encrypted message iv: IV used to encrypt `encrypted` returns: True if decryption of `encrypted` has valid padding False otherwise """ blksize = len(CONSISTENT_KEY) cipher = AES.new(CONSISTENT_KEY, AES.MODE_ECB) cbc = CBCMode(blksize=blksize, encrypt_blk=cipher.encrypt, decrypt_blk=cipher.decrypt, iv=iv) decrypted = cbc.decrypt(encrypted) try: PKCS7Padding.unapply(decrypted) return True except InvalidPaddingException: return False
def main(): """ decrypt contents of a file encrypted using AES-128 in CBC mode """ key = b"YELLOW SUBMARINE" iv = bytes(16) cipher = AES.new(key, AES.MODE_ECB) cbc = CBCMode( blksize=16, encrypt_blk=cipher.encrypt, decrypt_blk=cipher.decrypt, iv=iv ) input_filename = os.path.join(pathlib.Path(__file__).parent, "input") with open(input_filename, 'r') as input_file: base64_str = input_file.read() base64_bytes = base64_str.replace('\n', '').encode("utf-8") encrypted = base64.decodebytes(base64_bytes) message = cbc.decrypt(encrypted) print(message.decode("utf-8", errors="ignore"))