diff --git a/TPs/TP03/Readme.md b/TPs/TP03/Readme.md new file mode 100644 index 0000000..a469ec8 --- /dev/null +++ b/TPs/TP03/Readme.md @@ -0,0 +1,8 @@ +# Questao 1 + +Ao utilizar o programa 'chacha20_int_attck.py' sobre um criptograma produzido por 'pbenc_chacha20_poly1305', the decrpyt function will raise the execption : +- 'cryptography.exceptions.InvalidTag' – If the authentication tag doesn’t validate this exception will be raised. This will occur when the ciphertext has been changed, but will also occur when the key, nonce, or associated data are wrong. + +We can try this by encrypting a message and then changing the ciphertext with the attack program: + +[Failed Attack](https://github.com/uminho-mei-es/2324-G05/tree/main/TPs/TP03/images/failed_attack.png) \ No newline at end of file diff --git a/TPs/TP03/attack_fail.png b/TPs/TP03/attack_fail.png new file mode 100644 index 0000000..f489c7a Binary files /dev/null and b/TPs/TP03/attack_fail.png differ diff --git a/TPs/TP03/py/chacha20_int_attck.py b/TPs/TP03/py/chacha20_int_attck.py new file mode 100644 index 0000000..60ad33c --- /dev/null +++ b/TPs/TP03/py/chacha20_int_attck.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python3 + +import sys + +def attack(fctxt, pos, plainAtPos, newPlainAtPos): + f = open(fctxt,"rb") + ciphertext = f.read() + f.close() + + plainAtPos = plainAtPos.encode() + newPlainAtPos = newPlainAtPos.encode() + txt_len = len(plainAtPos) + diff = bytes([a ^ b for (a,b) in zip(plainAtPos,newPlainAtPos)]) + cipher_diff = bytes([a ^ b for (a,b) in zip(diff,ciphertext[pos:pos+txt_len])]) + + new_ciphertext = ciphertext[:pos] + cipher_diff + ciphertext[pos+txt_len:] + + with open(fctxt+".attck","wb") as f: + f.write(new_ciphertext) + +def main(): + argv = sys.argv[1:] + argc = len(argv) + if argc < 3 or argc > 5: + sys.exit("Needs 4 arguments ") + + attack(argv[0],int(argv[1]),argv[2],argv[3]) + +if __name__ == "__main__": + main() diff --git a/TPs/TP03/py/pbenc_chacha20_poly1305.py b/TPs/TP03/py/pbenc_chacha20_poly1305.py index ff1ea73..714793c 100644 --- a/TPs/TP03/py/pbenc_chacha20_poly1305.py +++ b/TPs/TP03/py/pbenc_chacha20_poly1305.py @@ -40,7 +40,13 @@ def decrypt(input_file, key_file): cipher = ChaCha20Poly1305(key) - plaintext = cipher.decrypt(nonce, ciphertext, aad) + try: + plaintext = cipher.decrypt(nonce, ciphertext, aad) + except Exception as e: + print(f"Could not validate the authentication: {e}") + return + + with open(f"{input_file}.dec", "wb") as f: f.write(plaintext)