溫馨提示×

Python加密與解密實踐經(jīng)驗

小樊
81
2024-11-02 18:20:35
欄目: 編程語言

在Python中實現(xiàn)加密和解密有很多方法,這里我將介紹兩種常用的加密算法:AES(高級加密標(biāo)準(zhǔn))和DES(數(shù)據(jù)加密標(biāo)準(zhǔn))。同時,我會使用pycryptodome庫來簡化操作。

首先,確保已經(jīng)安裝了pycryptodome庫。如果沒有安裝,可以使用以下命令安裝:

pip install pycryptodome

接下來,我們將分別介紹AES和DES的加密和解密實現(xiàn)。

AES加密與解密

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)字節(jié)
plaintext = b'Hello, World!'

ciphertext = aes_encrypt(key, plaintext)
print(f'加密后的文本: {ciphertext}')

decrypted_text = aes_decrypt(key, ciphertext)
print(f'解密后的文本: {decrypted_text}')

DES加密與解密

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字節(jié)
plaintext = b'Hello, World!'

ciphertext = des_encrypt(key, plaintext)
print(f'加密后的文本: {ciphertext}')

decrypted_text = des_decrypt(key, ciphertext)
print(f'解密后的文本: {decrypted_text}')

以上代碼展示了如何使用AES和DES算法進(jìn)行加密和解密。請注意,密鑰的長度和加密模式可能會影響加密的安全性。在實際應(yīng)用中,請確保使用合適的密鑰長度和加密模式。

0