fanqie
fanqie

Reputation: 1

How do I solve encountered error binascii Odd-length String?

I have tried the below AES GCM 256 Algorithm using hexlify and unhexlify. However, I have encountered the odd-length string binascii error. I am new to the Cybersecurity field. Would be much appreciated if anyone could assist me with the below codes I have tried.

I searched and used another methods like binascii.unhexlify('0%x' % n) but it does not work.

def encrypt_AES_GCM_256(message: str):
    key = common.AES_GCM_ALGO_KEY.encode('utf-8') # fixed key of 32 bytes (generated from import secrets)
    nonce = get_random_bytes(12)  # generate a random nonce

    cipher = AES.new(key, AES.MODE_GCM, nonce=nonce)
    ciphertext_bytes, tag = cipher.encrypt_and_digest(message.encode('utf-8'))
    nonce_and_ciphertext_tag = nonce + ciphertext_bytes + tag  # prepend nonce and append tag
    return hexlify(nonce_and_ciphertext_tag).decode('utf-8')

def decrypt_AES_GCM_256(encrypted_message: str):
    key = common.AES_GCM_ALGO_KEY.encode('utf-8') # fixed key of 32 bytes

    # unhexlify the formatted string --> unhexlify need to read in even encrypted message
    nonce_and_ciphertext_and_tag = unhexlify(encrypted_message)

    nonce = nonce_and_ciphertext_and_tag[:12]  # extract nonce
    ciphertext = nonce_and_ciphertext_and_tag[12:-16]  # exclude the nonce and tag from ciphertext
    tag = nonce_and_ciphertext_and_tag[-16:]  # extract tag

    cipher = AES.new(key, AES.MODE_GCM, nonce=nonce)
    plaintext_bytes = cipher.decrypt_and_verify(ciphertext, tag)
    return plaintext_bytes.decode('utf-8')

Upvotes: 0

Views: 81

Answers (0)

Related Questions