Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

python加密代码

作者:死亡之神   发布日期:2025-10-24   浏览:95

# Python加密代码示例:使用Fernet对称加密

from cryptography.fernet import Fernet

# 生成密钥并保存到文件
def generate_key():
    key = Fernet.generate_key()
    with open("secret.key", "wb") as key_file:
        key_file.write(key)

# 加载密钥
def load_key():
    return open("secret.key", "rb").read()

# 加密消息
def encrypt_message(message):
    key = load_key()
    f = Fernet(key)
    encrypted_message = f.encrypt(message.encode())
    return encrypted_message

# 解密消息
def decrypt_message(encrypted_message):
    key = load_key()
    f = Fernet(key)
    decrypted_message = f.decrypt(encrypted_message)
    return decrypted_message.decode()

# 示例用法
if __name__ == "__main__":
    # 生成并保存密钥
    generate_key()

    # 要加密的消息
    message = "这是一个秘密消息"

    # 加密消息
    encrypted = encrypt_message(message)
    print(f"加密后的消息: {encrypted}")

    # 解密消息
    decrypted = decrypt_message(encrypted)
    print(f"解密后的消息: {decrypted}")

解释说明:

  1. 生成密钥generate_key() 函数用于生成一个随机的加密密钥,并将其保存到文件 secret.key 中。这个密钥将用于加密和解密操作。
  2. 加载密钥load_key() 函数从文件中读取之前生成的密钥。
  3. 加密消息encrypt_message(message) 函数接收一个字符串消息,使用加载的密钥对其进行加密,并返回加密后的字节串。
  4. 解密消息decrypt_message(encrypted_message) 函数接收一个加密后的字节串,使用加载的密钥对其进行解密,并返回原始的字符串消息。
  5. 示例用法:在主程序中,首先生成并保存密钥,然后对一个示例消息进行加密和解密,并打印结果。

这个示例展示了如何使用 Python 的 cryptography 库中的 Fernet 类来进行对称加密和解密。

上一篇:python闭包函数的作用

下一篇:python字典转字符串

大家都在看

python时间格式

python读取文件路径

staticmethod在python中有

python开发windows应用程序

python中len是什么意思

python ord和chr

python中的yield

python自定义异常

python判断路径是否存在

python list.pop

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站