今天來學習區塊加密演算法的AES-GCM
AES採用128位元的區塊長度,通常是128位元,也可以是192、256位元長度的金鑰。
GCM模式中可以進行並行加密,效率也比較好,並且會提供一次性數字(Nonce)和訊息驗證碼(Tag),尤其是nonce和tag在解密之中起到非常重要的功能,用以檢驗密文的完整性,防止未經授權的篡改
先安裝python 的 pycryptodome 模組
pip install pycryptodome
生成一個128元的密鑰
利用encrypt_AES_GCM()函數對plaintext 加密得到Nonce、tag 和ciphertext
利用decrypt_AES_GCM()函數對ciphertext解密,需要用到密鑰、Nonce、tag,便得到原始的plaintext
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
def encrypt_AES_GCM(key, plaintext):
# Create a new AES-GCM cipher object with the provided key
cipher = AES.new(key, AES.MODE_GCM)
# Encrypt the plaintext and obtain the ciphertext and authentication tag
ciphertext, tag = cipher.encrypt_and_digest(plaintext.encode())
# Return the ciphertext, nonce, and authentication tag
return ciphertext, cipher.nonce, tag
def decrypt_AES_GCM(key, nonce, ciphertext, tag):
# Create a new AES-GCM cipher object with the provided key and nonce
cipher = AES.new(key, AES.MODE_GCM, nonce=nonce)
# Decrypt the ciphertext and verify its authenticity using the tag
plaintext = cipher.decrypt_and_verify(ciphertext, tag)
# Return the decrypted plaintext as a string
return plaintext.decode()
# Usage example
if __name__ == "__main__":
key = get_random_bytes(16) # 128-bit key
plaintext = "Happy Moon Festival!" # The plaintext to encrypt
# Encrypt the plaintext
ciphertext, nonce, tag = encrypt_AES_GCM(key, plaintext)
print("Ciphertext:", ciphertext.hex())
print("Nonce:", nonce.hex())
print("Tag:", tag.hex())
# Decrypt the ciphertext
decrypted_text = decrypt_AES_GCM(key, nonce, ciphertext, tag)
print("Decrypted Text:", decrypted_text)
Ciphertext: 7357fa3bb68da8cd111b50529dae593e015a384cc02b
Nonce: 78284dffdf5b9031a17e0355ace1ed2f
Tag: 00b21966b7fb949889de642730d895f3
Decrypted Text: Happy Moon Festival!
心得:各位中秋節快樂= =