0

What is the correct way to encrypt data via AES-GCM in Python to be decryptable with Web cryptographic API? (using PyCryptodome) Since PyCryptodome uses nonce and WCA IV. Is it a problem?

Python:

from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes

key = get_random_bytes(16)
nonce = get_random_bytes(16)
cipher = AES.new(key, AES.MODE_GCM, nonce=nonce)
ciphertext, tag = cipher.encrypt_and_digest(data)

file_out = open("encrypted.bin", "wb")
[ file_out.write(x) for x in (cipher.nonce, tag, ciphertext) ]

Javascript:

window.crypto.subtle.importKey(
    "jwk", //can be "jwk" or "raw"
    {   //this is an example jwk key, "raw" would be an ArrayBuffer
        kty: "oct",
        k: jwk_key,
        alg: "A128GCM",
        ext: true,
    },
    {   //this is the algorithm options
        name: "AES-GCM",
    },
    false, //whether the key is extractable (i.e. can be used in exportKey)
    ["encrypt", "decrypt"] //can "encrypt", "decrypt", "wrapKey", or "unwrapKey"
)
.then(function(key){
    //returns the symmetric key
    console.log(key);
    window.crypto.subtle.decrypt(
        {
            name: "AES-GCM",
            iv: nonce_from_python, //The initialization vector you used to     encrypt
        //additionalData: ArrayBuffer, //The addtionalData you used to encrypt     (if any)
            tagLength: 128, //The tagLength you used to encrypt (if any)
        },
        key, //from generateKey or importKey above
        data //ArrayBuffer of the data
    )
    .then(function(decrypted){
        //returns an ArrayBuffer containing the decrypted data
        console.log(new Uint8Array(decrypted));
    })
    .catch(function(err){
        console.error(err);
    });
})
.catch(function(err){
    console.error(err);
});
d3im
  • 323
  • 2
  • 4
  • 18

1 Answers1

0

As far as I understand, webcrypto encrypts into ciphertext+tag. Therefor, in your python code, try changing

[ file_out.write(x) for x in (cipher.nonce, tag, ciphertext) ]

to

file_out.write(ciphertext)
file_out.write(tag)

The IV (nonce) will be needed to be passed separately.

LiraNuna
  • 64,916
  • 15
  • 117
  • 140