要实现AES GCM加密和解密的互相兼容性,需要使用相同的密钥、初始向量(IV)和附加数据(AAD)。以下是一个使用Python的代码示例:
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from Crypto.Random import get_random_bytes
def encrypt(plaintext, key):
cipher = AES.new(key, AES.MODE_GCM)
cipher.update(b"additional data") # 添加附加数据
ciphertext, tag = cipher.encrypt_and_digest(plaintext)
return cipher.nonce + ciphertext + tag
def decrypt(ciphertext, key):
nonce = ciphertext[:16]
tag = ciphertext[-16:]
ciphertext = ciphertext[16:-16]
cipher = AES.new(key, AES.MODE_GCM, nonce=nonce)
cipher.update(b"additional data") # 添加附加数据
plaintext = cipher.decrypt_and_verify(ciphertext, tag)
return plaintext
# 生成随机密钥
key = get_random_bytes(16)
# 加密
plaintext = b"Hello, AES-GCM!"
ciphertext = encrypt(plaintext, key)
print("Ciphertext:", ciphertext)
# 解密
decrypted_plaintext = decrypt(ciphertext, key)
print("Decrypted plaintext:", decrypted_plaintext)
在上述代码中,encrypt函数使用AES GCM模式进行加密,并将附加数据与密文一起返回。decrypt函数使用相同的密钥、IV和附加数据来解密密文,并返回明文。
请注意,代码示例中使用了Crypto库来进行AES加密和解密操作。您需要确保已安装此库,可以使用pip install pycryptodome命令进行安装。