一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

TextBlob如何实现文本加密与解密

时间:2026-05-31 10:00:01 编辑:袖梨 来源:一聚教程网

虽然TextBlob库专注于文本分析处理,但实现加密功能需借助专业加密工具。本文将详细介绍如何通过Python的Crypto库实现文本的AES加密解密操作。

TextBlob中怎么加密和解密文本

from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
import base64

def encrypt_text(key, text):
    cipher = AES.new(key, AES.MODE_EAX)
    ciphertext, tag = cipher.encrypt_and_digest(text.encode())
    return base64.b64encode(cipher.nonce + tag + ciphertext)

def decrypt_text(key, encrypted_text):
    encrypted_text = base64.b64decode(encrypted_text)
    nonce = encrypted_text[:AES.block_size]
    tag = encrypted_text[AES.block_size:AES.block_size+16]
    ciphertext = encrypted_text[AES.block_size+16:]
    cipher = AES.new(key, AES.MODE_EAX, nonce)
    decrypted_text = cipher.decrypt_and_verify(ciphertext, tag)
    return decrypted_text.decode()

# Generate a random key
key = get_random_bytes(16)
# Encrypt text
text = "Hello, world!"
encrypted_text = encrypt_text(key, text)
print("Encrypted text:", encrypted_text)
# Decrypt text
decrypted_text = decrypt_text(key, encrypted_text)
print("Decrypted text:", decrypted_text)

通过上述AES加密方案,我们可以有效保护文本数据安全,但切记密钥管理是保障加密效果的关键环节。

热门栏目