在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算法進行加密和解密。請注意,密鑰的長度和加密模式可能會影響加密的安全性。在實際應用中,請確保使用合適的密鑰長度和加密模式。