page contents

Python 安全框架 cryptography:最好用的加密库,让数据更安全!

今天让我们一起探索Python中非常重要的一个安全主题 - cryptography加密库。在当今数据安全日益重要的环境下,掌握基本的加密解密技能变得尤为关键。这个强大的库不仅可以帮助我们保护敏感数据,还能让我们深入理解现代密码学的精髓。让我们开始这次的安全之旅吧!

attachments-2024-12-MCZu8o49675f83da5a4e4.png

今天让我们一起探索Python中非常重要的一个安全主题 - cryptography加密库。在当今数据安全日益重要的环境下,掌握基本的加密解密技能变得尤为关键。这个强大的库不仅可以帮助我们保护敏感数据,还能让我们深入理解现代密码学的精髓。让我们开始这次的安全之旅吧!

1. 初识cryptography

cryptography是Python中最受欢迎的加密库,它提供了丰富的加密算法和工具。我们先来安装这个库:

# 使用pip安装cryptography

pip install cryptography

2. 对称加密:Fernet

最简单好用的要数Fernet对称加密了!它使用相同的密钥进行加密和解密,特别适合保护配置文件、密码等敏感数据。

from cryptography.fernet import Fernet

# 生成密钥

key = Fernet.generate_key()

f = Fernet(key)

# 加密文本

message = "我的银行密码是8888"

encrypted_message = f.encrypt(message.encode())

print("加密后:", encrypted_message)

# 解密文本

decrypted_message = f.decrypt(encrypted_message).decode()

print("解密后:", decrypted_message)

小贴士: 一定要安全地保存密钥!如果密钥丢失,加密的数据将永远无法恢复。

3. 密码哈希:保护用户密码

在实际应用中,我们通常不会直接存储用户密码,而是存储密码的哈希值。来看看如何使用cryptography实现:

from cryptography.hazmat.primitives import hashes

from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC

import os

def hash_password(password):

    # 生成随机盐值

    salt = os.urandom(16)

    # 创建PBKDF2HMAC对象

    kdf = PBKDF2HMAC(

        algorithm=hashes.SHA256(),

        length=32,

        salt=salt,

        iterations=100000,

    )   

    # 生成密码哈希

    key = kdf.derive(password.encode())

    return salt, key

# 示例使用

password = "my_secure_password123"

salt, key = hash_password(password)

print("盐值:", salt)

print("密码哈希:", key)

4. 文件加密:保护敏感文档

让我们来实现一个简单的文件加密功能:

def encrypt_file(filename, key):

    f = Fernet(key)    

    with open(filename, 'rb') as file:

        file_data = file.read()   

    # 加密文件数据

    encrypted_data = f.encrypt(file_data)

    # 写入加密后的文件

    with open(filename + '.encrypted', 'wb') as file:

        file.write(encrypted_data)

def decrypt_file(filename, key):

    f = Fernet(key) 

    with open(filename, 'rb') as file:

        encrypted_data = file.read()

    # 解密文件数据

    decrypted_data = f.decrypt(encrypted_data)

    # 写入解密后的文件

    with open('decrypted_' + filename, 'wb') as file:

        file.write(decrypted_data)

# 使用示例

key = Fernet.generate_key()

encrypt_file('secret.txt', key)

decrypt_file('secret.txt.encrypted', key)

小贴士: 在处理大文件时,最好分块读取和加密,以避免内存占用过大。

5. 实战练习:创建密码管理器

下面是一个简单的密码管理器示例,供大家练习:

from cryptography.fernet import Fernet

import json

class PasswordManager:

    def __init__(self, master_password):

        # 使用主密码生成加密密钥

        self.key = Fernet.generate_key()

        self.cipher_suite = Fernet(self.key)

        self.passwords = {}

    def add_password(self, service, password):

        # 加密存储密码

        encrypted_password = self.cipher_suite.encrypt(password.encode())

        self.passwords[service] = encrypted_password

    def get_password(self, service):

        # 解密获取密码

        if service in self.passwords:

            return self.cipher_suite.decrypt(self.passwords[service]).decode()

        return None

# 使用示例

pm = PasswordManager("master_password")

pm.add_password("gmail", "my_gmail_password")

pm.add_password("github", "my_github_password")

print(pm.get_password("gmail"))  # 输出: my_gmail_password

今天的Python学习之旅就到这里啦!记得动手敲代码,尤其要注意密钥的安全保管。在实际项目中,建议将密钥存储在环境变量或专门的密钥管理服务中。祝大家学习愉快,Python学习节节高!

更多相关技术内容咨询欢迎前往并持续关注好学星城论坛了解详情。

想高效系统的学习Python编程语言,推荐大家关注一个微信公众号:Python编程学习圈。每天分享行业资讯、技术干货供大家阅读,关注即可免费领取整套Python入门到进阶的学习资料以及教程,感兴趣的小伙伴赶紧行动起来吧。

attachments-2022-05-rLS4AIF8628ee5f3b7e12.jpg

  • 发表于 2024-12-16 09:35
  • 阅读 ( 107 )
  • 分类:Python开发

你可能感兴趣的文章

相关问题

0 条评论

请先 登录 后评论
小柒
小柒

1734 篇文章

作家榜 »

  1. 轩辕小不懂 2403 文章
  2. 小柒 1734 文章
  3. Pack 1135 文章
  4. Nen 576 文章
  5. 王昭君 209 文章
  6. 文双 71 文章
  7. 小威 64 文章
  8. Cara 36 文章