使用更加安全的加密模式,例如CBC模式或CTR模式。
示例代码(Python实现AES CBC模式加密解密):
import os from Crypto.Cipher import AES
class AESCipher:
def __init__(self, key):
self.key = key
def encrypt(self, raw):
"""
Encrypts the raw data using AES CBC mode
:param raw: The data to encrypt
:return: The encrypted data
"""
raw = self._pad(raw)
iv = os.urandom(AES.block_size)
cipher = AES.new(self.key, AES.MODE_CBC, iv)
return iv + cipher.encrypt(raw)
def decrypt(self, enc):
"""
Decrypts the encrypted data using AES CBC mode
:param enc: The encrypted data
:return: The decrypted data
"""
iv = enc[:AES.block_size]
cipher = AES.new(self.key, AES.MODE_CBC, iv)
raw = cipher.decrypt(enc[AES.block_size:])
return self._unpad(raw).decode('utf-8')
def _pad(self, s):
"""
Pads the given string to be a multiple of 16 bytes
:param s: The string to pad
:return: The padded string
"""
return s + (AES.block_size - len(s) % AES.block_size) * chr(AES.block_size - len(s) % AES.block_size)
@staticmethod
def _unpad(s):
"""
Removes padding from a given string
:param s: The string to remove padding from
:return: The unpadded string
"""
return s[:-ord(s[len(s) - 1:])]
key = b"super_secret_key" cipher = AESCipher(key) enc = cipher.encrypt("hello world") print(enc) dec = cipher.decrypt(enc) print(dec)