@nakov/

AES-256-GCM wrong chiphertext in Python

Python

AES-256-GCM example with wrong chipgertext in Python

fork
loading
Files
  • main.py
  • requirements.txt
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
from Crypto.Cipher import AES
import binascii, os

def encrypt_AES_GCM(msg, secretKey):
    aesCipher = AES.new(secretKey, AES.MODE_GCM)
    ciphertext, authTag = aesCipher.encrypt_and_digest(msg)
    return (ciphertext, aesCipher.nonce, authTag)

def decrypt_AES_GCM(encryptedMsg, secretKey):
    (ciphertext, nonce, authTag) = encryptedMsg
    aesCipher = AES.new(secretKey, AES.MODE_GCM, nonce)
    plaintext = aesCipher.decrypt_and_verify(ciphertext, authTag)
    return plaintext

secretKey = os.urandom(32) # 256-bit random encryption key
# print("Encryption key:", binascii.hexlify(secretKey))

msg = b'Message for AES-256-GCM + Scrypt encryption'
encryptedMsg = encrypt_AES_GCM(msg, secretKey)
# print("encryptedMsg", {
# 'ciphertext': binascii.hexlify(encryptedMsg[0]),
# 'aesIV': binascii.hexlify(encryptedMsg[1]),
# 'authTag': binascii.hexlify(encryptedMsg[2])
# })

decryptedMsg = decrypt_AES_GCM(encryptedMsg, secretKey)
# print("decryptedMsg", decryptedMsg)

encryptedMsg = (b'wrong chiphertext', encryptedMsg[1], encryptedMsg[2])
decryptedMsg = decrypt_AES_GCM(encryptedMsg, secretKey) # ValueError: MAC check failed