Generating AES 256 GCM secret using a given key in python

Viewed 891

I am trying to Implement AES encryption in python.
I am referring a java code sample in order to accomplish this.
In Java, the 256 bit secret (using the given key) is generated using

Key secretKey = new SecretKeySpec(Base64.decodeBase64(GIVEN_KEY), "AES");

I am trying to do the same in python using the following snippet

secret = hashlib.sha256(GIVEN_KEY.encode()).digest()

But the string encoded with python implementation is not being able to get decrypted. Is the above snippets similar, or is there anything I am missing?

1 Answers

In Java the Base64 decoded value of GIVEN_KEY is used as key, in Python, the SHA256 hash of GIVEN_KEY. Both are not the same.

The counterpart in Python would be something like:

import base64
...
secret = base64.b64decode(GIVEN_KEY.encode()) # by default UTF8 encoded

EDIT: In the linked code (p. 31) the key is Base64url encoded without padding:

QOahfcdo98NLjYJuhP4-VKigx51NkUETsKlIu9uXZFY

which can be recognized by the character - and the length which is not divisible by 4.

This corresponds Base64url decoded to the byte sequence

40e6a17dc768f7c34b8d826e84fe3e54a8a0c79d4d914113b0a948bbdb976456

which represents a 32 bytes key (AES-256) and can be tested e.g. here.

In Python you can Base64url decode with urlsafe_b64decode. However, a padded Base64url encoded value is expected, so that the padding has to be added first, e.g. with the repad method from here.

import base64

# from https://stackoverflow.com/a/9024884/9014097
def repad(data):
    return data + "=" * (-len(data)%4)

GIVEN_KEY = 'QOahfcdo98NLjYJuhP4-VKigx51NkUETsKlIu9uXZFY'

secret = base64.urlsafe_b64decode(repad(GIVEN_KEY).encode()) 
print(secret.hex()) # 40e6a17dc768f7c34b8d826e84fe3e54a8a0c79d4d914113b0a948bbdb976456
Related