在 Python 中通过 AES-GCM 加密数据以使用 Web 加密 API 解密的正确方法是什么?(使用 PyCryptodome)因为 PyCryptodome 使用 nonce 和 WCA IV。这是个问题吗?
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);
});