在Python中实现加密和解密有很多方法,这里我将介绍两种常用的加密算法:AES(高级加密标准)和DES(数据加密标准)。同时,我会使用pycryptodome
库来简化操作。
首先,确保已经安装了pycryptodome
库。如果没有安装,可以使用以下命令安装:
pip install pycryptodome
接下来,我们将分别介绍AES和DES的加密和解密实现。
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from Crypto.Util.Padding import pad, unpad
import base64
def aes_encrypt(key, plaintext):
cipher = AES.new(key, AES.MODE_CBC)
ct_bytes = cipher.encrypt(pad(plaintext, AES.block_size))
iv = base64.b64encode(cipher.iv).decode('utf-8')
ct = base64.b64encode(ct_bytes).decode('utf-8')
return iv + ':' + ct
def aes_decrypt(key, ciphertext):
iv, ct = ciphertext.split(':')
iv = base64.b64decode(iv)
ct = base64.b64decode(ct)
cipher = AES.new(key, AES.MODE_CBC, iv)
return unpad(cipher.decrypt(ct), AES.block_size).decode('utf-8')
# 示例
key = get_random_bytes(16) # AES密钥长度可以是16(AES-128)、24(AES-192)或32(AES-256)字节
plaintext = b'Hello, World!'
ciphertext = aes_encrypt(key, plaintext)
print(f'加密后的文本: {ciphertext}')
decrypted_text = aes_decrypt(key, ciphertext)
print(f'解密后的文本: {decrypted_text}')
from Crypto.Cipher import DES
from Crypto.Random import get_random_bytes
from Crypto.Util.Padding import pad, unpad
import base64
def des_encrypt(key, plaintext):
cipher = DES.new(key, DES.MODE_CBC)
ct_bytes = cipher.encrypt(pad(plaintext, DES.block_size))
iv = base64.b64encode(cipher.iv).decode('utf-8')
ct = base64.b64encode(ct_bytes).decode('utf-8')
return iv + ':' + ct
def des_decrypt(key, ciphertext):
iv, ct = ciphertext.split(':')
iv = base64.b64decode(iv)
ct = base64.b64decode(ct)
cipher = DES.new(key, DES.MODE_CBC, iv)
return unpad(cipher.decrypt(ct), DES.block_size).decode('utf-8')
# 示例
key = get_random_bytes(8) # DES密钥长度必须是8字节
plaintext = b'Hello, World!'
ciphertext = des_encrypt(key, plaintext)
print(f'加密后的文本: {ciphertext}')
decrypted_text = des_decrypt(key, ciphertext)
print(f'解密后的文本: {decrypted_text}')
以上代码展示了如何使用AES和DES算法进行加密和解密。请注意,密钥的长度和加密模式可能会影响加密的安全性。在实际应用中,请确保使用合适的密钥长度和加密模式。