通过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);
});
答案 0 :(得分:0)
据我了解,webcrypto加密为ciphertext
+ tag
。
因此,在你的python代码中,尝试更改
[ file_out.write(x) for x in (cipher.nonce, tag, ciphertext) ]
到
file_out.write(ciphertext)
file_out.write(tag)
IV(nonce)将需要单独传递。