python数据加密代码怎么写

43次阅读
没有评论

共计 936 个字符,预计需要花费 3 分钟才能阅读完成。

在 Python 中,可以使用各种算法对数据进行加密。以下是使用 AES 算法对数据进行加密和解密的示例代码:

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

def encrypt_data(data, key):
    cipher = AES.new(key, AES.MODE_EAX)
    nonce = cipher.nonce
    ciphertext, tag = cipher.encrypt_and_digest(data)
    return nonce + ciphertext + tag

def decrypt_data(encrypted_data, key):
    nonce = encrypted_data[:16]
    ciphertext = encrypted_data[16:-16]
    tag = encrypted_data[-16:]
    cipher = AES.new(key, AES.MODE_EAX, nonce)
    decrypted_data = cipher.decrypt_and_verify(ciphertext, tag)
    return decrypted_data

# 随机生成 16 字节的密钥
key = get_random_bytes(16)

# 要加密的数据
data = b"Hello, World!"

# 加密数据
encrypted_data = encrypt_data(data, key)
print(" 加密后的数据:", encrypted_data)

# 解密数据
decrypted_data = decrypt_data(encrypted_data, key)
print(" 解密后的数据:", decrypted_data.decode())

请注意,这个例子使用了 Crypto 模块,它需要安装 pycryptodome 库。你可以使用 pip 命令安装它:

pip install pycryptodome

此代码使用 AES 算法使用 16 字节的密钥对数据进行加密和解密。加密后的数据包括一个 16 字节的随机生成的 nonce,加密的数据本身,以及一个 16 字节的 tag,用于验证数据的完整性。在解密时,需要使用相同的密钥和 nonce 来解密数据并验证 tag。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-13发表,共计936字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)