📅  最后修改于: 2023-12-03 15:12:56.584000             🧑  作者: Mango
AES 是一种对称加密算法,它是目前最流行的加密标准之一。该算法采用块加密的方式,将明文分块加密,每个块的大小为 128 位。AES 算法有三种密钥长度可供选择,分别是 128 位、192 位、256 位。
以下是 Python 中使用 AES 算法加密和解密字符串的示例代码:
import base64
from Crypto.Cipher import AES
def pad(s):
return s + b"\0" * (AES.block_size - len(s) % AES.block_size)
def encrypt(message, key):
message = pad(message)
iv = b'Sixteen byte iv'
cipher = AES.new(key, AES.MODE_CBC, iv)
encrypted = cipher.encrypt(message)
return base64.b64encode(encrypted).decode('utf-8')
def decrypt(ciphertext, key):
ciphertext = base64.b64decode(ciphertext)
iv = b'Sixteen byte iv'
cipher = AES.new(key, AES.MODE_CBC, iv)
decrypted = cipher.decrypt(ciphertext)
return decrypted.rstrip(b"\0").decode('utf-8')
以上代码使用了 pycryptodome
库中的 AES 实现,需要先通过 pip install pycryptodome
命令安装。
其中 pad
函数用于补齐明文,使其长度为 AES 块大小的整数倍。encrypt
函数使用 CBC 模式对明文进行加密,并进行 Base64 编码。decrypt
函数对密文进行 Base64 解码,并使用相同的密钥和 IV 进行解密操作。
AES 算法目前尚未被攻破,但是密钥长度越长,算法越安全的说法已经被证明是不正确的。即使使用 128 位密钥,如果使用的密码学工具存在漏洞,也可能被破解。
因此,在选择加密算法时,不仅需要考虑算法的安全性,还需要考虑实现的安全性和密码学工具的安全性。常见的密码学工具包括 OpenSSL、Libsodium 等。