用Python和 Cryptography库给你的文件加密解密

本文详细介绍了如何使用Python的Cryptography库进行文件加密和解密,包括基本概念、库的特点、Fernet对称加密示例以及高级组件hazmat的应用。还展示了如何在GUI应用中集成加密功能,以及使用RSA进行非对称加密的简单示例。
摘要由CSDN通过智能技术生成

用Python和 Cryptography库给你的文件加密解密

用Python和 Cryptography库给你的文件加把安全锁。

先介绍与加密解密有关的几个基本概念。

加密(Encryption):加密是将明文转换为密文的过程,使得未经授权的人无法读懂。

解密(Decryption):解密是将密文转换为明文的过程,使得原始信息可以被正确的人阅读。

密钥(Key):密钥是加密和解密过程中的关键。它可以是单个数字、字符串或者是更复杂的密钥对象。

算法:算法是加密和解密过程中的具体步骤。

cryptography是一个强大的Python库,提供了一套丰富的加密相关的操作,用于安全地处理数据。它旨在提供简单易用的加密方法,同时也支持更高级的加密需求,使这项技术变得易于使用。cryptography库包含两个主要的高级组件:Fernet(对称加密)和hazmat(危险材料层)。

主要特点

易用性:cryptography库的设计初衷是易于使用,尽量减少安全漏洞的出现。

安全性:它提供了最新的加密算法,并且经过安全专家的审查。

灵活性:对于需要直接访问加密算法的高级用户,cryptography提供了hazmat模块。

主要组件

Fernet:提供了对称加密的实现,非常适合用于加密和解密可以安全共享密钥的场景。使用Fernet非常简单,只需要一个密钥就可以进行安全的数据加密和解密。

hazmat(Hazardous Materials):这个模块提供了底层加密原语(如块密码、消息摘要算法等)。它是为那些需要执行特定加密操作的高级用户设计的,但使用时需要格外小心,因为不当的使用可能导致安全问题。

官方文档https://cryptography.io/en/latest/

在Windows平台上安装cryptography,可在cmd命令行中,输入如下命令:

pip install cryptography

回车,默认情况使用国外线路较慢,我们可以使用国内的镜像网站:

豆瓣:https://pypi.doubanio.com/simple/

清华:https://pypi.tuna.tsinghua.edu.cn/simple

电脑上安装了多个Python版本,你可以为特定版本的Python安装模块(库、包)。例如我的电脑中安装了多个Python版本,要在Python 3.10版本中安装,并使用清华的镜像,cmd命令行中,输入如下命令

py -3.10 -m pip install cryptography -i https://pypi.tuna.tsinghua.edu.cn/simple

简单示例:使用Fernet进行数据加密和解密源码:

from cryptography.fernet import Fernet

# 生成密钥
key = Fernet.generate_key()
cipher_suite = Fernet(key)

# 加密数据
data = b"Hello, cryptography!"
encrypted_data = cipher_suite.encrypt(data)
print(f"Encrypted: {encrypted_data}")

# 解密数据
decrypted_data = cipher_suite.decrypt(encrypted_data)
print(f"Decrypted: {decrypted_data}")

运行效果:

图形用户界面的文件加密解密程序

使用tkinter添加界面的加密解密程序,当用户点击“加密文件”或“解密文件”按钮时,程序会从这个文本框中获取密钥,并使用它进行相应的加密或解密操作。加密和解密的文件将会被保存在与原文件相同的目录下,加密文件的文件名在原图片文件名前添加enc_,解密文件的文件名在原加密图片文件名前添加dec_

先给出运行效果:

源码如下:

import tkinter as tk
from tkinter import filedialog
from cryptography.fernet import Fernet
import os

def encrypt(filename, key, status_label):
    try:
        f = Fernet(key.encode())  # 将密钥从字符串转换为字节
        with open(filename, "rb") as file:
            file_data = file.read()
        encrypted_data = f.encrypt(file_data)
        dir_name, base_filename = os.path.split(filename)
        # 分离目录和文件名
        encrypted_filename = f"enc_{base_filename}"
        # 将加密文件保存在原始目录中
        encrypted_file_path = os.path.join(dir_name, encrypted_filename)
        with open(encrypted_file_path, "wb") as file:
            file.write(encrypted_data)
        status_label.config(text=f"提示:文件已加密:{encrypted_filename}")
    except Exception as e:
        status_label.config(text=f"提示:加密失败: {str(e)}")

def decrypt(filename, key, status_label):
    try:
        f = Fernet(key.encode())  # 将密钥从字符串转换为字节
        with open(filename, "rb") as file:
            encrypted_data = file.read()
        decrypted_data = f.decrypt(encrypted_data)
        # 分离目录和文件名
        dir_name, base_filename = os.path.split(filename)
        decrypted_filename = f"dec_{base_filename}"
        # 将解密文件保存在原始目录中
        decrypted_file_path = os.path.join(dir_name, decrypted_filename)
        with open(decrypted_file_path, "wb") as file:
            file.write(decrypted_data)
        status_label.config(text=f"提示:文件已解密:{decrypted_filename}")
    except Exception as e:
        status_label.config(text=f"提示:解密失败: {str(e)}")

# 创建GUI界面
def select_file(operation, key_entry, status_label):
    key = key_entry.get()  # 从文本框获取密钥
    if not key:
        status_label.config(text="提示:操作失败:未输入密钥")
        return
    
    file_path = filedialog.askopenfilename()
    if file_path:  # 如果file_path不是空字符串
        if operation == 'encrypt':
            encrypt(file_path, key, status_label)
        elif operation == 'decrypt':
            decrypt(file_path, key, status_label)
    else:
        status_label.config(text="提示:没有选择文件")

def main():
    root = tk.Tk()
    root.title("加密解密程序")
    
    tk.Label(root, text="密钥:").pack()
    key_entry = tk.Entry(root, show='*', width=50)  # 密钥输入框
    key_entry.insert(0, 'X3Q8PvDs2EzKHK-8TjgUE8HkZ8QeuOe0S7-3VVqjTDI=') # 设置默认值  
    key_entry.pack()
    
    status_label = tk.Label(root, text="提示:请选择操作", height=2)
    status_label.pack()
    
    tk.Button(root, text="加密文件", command=lambda: select_file('encrypt', key_entry, status_label)).pack()
    tk.Button(root, text="解密文件", command=lambda: select_file('decrypt', key_entry, status_label)).pack()
    
    root.mainloop()

if __name__ == "__main__":
    main()

cryptography库提供了许多高级功能,提供了多种密码学算法,包括对称加密、非对称加密、哈希函数、签名、密钥管理等等。支持多种加密标准,包括AES、DES、RSA、SSL/TLS等等,同时也提供了许多密码学工具,如密码学随机数生成器、PBKDF2函数、密码学算法器等等。关于这些详情请阅读相关文档,在此仅举以下是一个简单的例子,展示了如何生成RSA密钥对、使用公钥进行加密以及使用私钥进行解密,源码如下:

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives import hashes

# 生成RSA密钥对
private_key = rsa.generate_private_key(
    public_exponent=65537,
    key_size=2048,
    backend=default_backend()
)
public_key = private_key.public_key()

# 将私钥序列化并保存到文件
with open("private_key.pem", "wb") as f:
    f.write(private_key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.PKCS8,
        encryption_algorithm=serialization.NoEncryption()
    ))

# 将公钥序列化并保存到文件
with open("public_key.pem", "wb") as f:
    f.write(public_key.public_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PublicFormat.SubjectPublicKeyInfo
    ))

# 读取公钥进行加密
with open("public_key.pem", "rb") as f:
    public_key = serialization.load_pem_public_key(
        f.read(),
        backend=default_backend()
    )

message = "Hello, RSA Cryptography!".encode()
encrypted = public_key.encrypt(
    message,
    padding.OAEP(
        mgf=padding.MGF1(algorithm=hashes.SHA256()),
        algorithm=hashes.SHA256(),
        label=None
    )
)

# 读取私钥进行解密
with open("private_key.pem", "rb") as f:
    private_key = serialization.load_pem_private_key(
        f.read(),
        password=None,
        backend=default_backend()
    )

original_message = private_key.decrypt(
    encrypted,
    padding.OAEP(
        mgf=padding.MGF1(algorithm=hashes.SHA256()),
        algorithm=hashes.SHA256(),
        label=None
    )
)

# 显示解密后的消息
print(original_message.decode())

这个例子首先生成了一个2048位的RSA密钥对,将私钥保存到private_key.pem文件中,将公钥保存到public_key.pem文件中。接下来,代码从public_key.pem文件中读取公钥用于加密消息,从private_key.pem文件中读取私钥用于解密消息。最后,使用公钥对一段消息进行加密,然后使用私钥将消息解密。padding.OAEP是一种常用的填充方式,与SHA-256哈希算法一起使用,以确保加密过程的安全性。

OK!

  • 22
    点赞
  • 41
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Python内置了一些加密模块,例如`cryptography`和`pycryptodome`等,可以用来实现对称加密文件并解密。 这里我们以`pycryptodome`为例,演示如何使用AES对称加密算法加密文件,并解密加密后的文件。 首先,你需要安装`pycryptodome`模块。你可以使用`pip`命令来进行安装: ``` pip install pycryptodome ``` 然后,你可以使用以下代码来实现对称加密文件: ```python from Crypto.Cipher import AES from Crypto.Random import get_random_bytes # 定义加密函数 def encrypt_file(key, in_filename, out_filename=None, chunksize=64*1024): # 如果没有指定输出文件名,则将输入文件名加上'.enc'后缀作为输出文件名 if not out_filename: out_filename = in_filename + '.enc' # 使用AES加密算法,ECB模式,PKCS7填充方式 cipher = AES.new(key, AES.MODE_ECB) # 获取随机数作为IV向量 iv = get_random_bytes(AES.block_size) # 打开输入文件和输出文件 with open(in_filename, 'rb') as infile: with open(out_filename, 'wb') as outfile: # 先将IV向量写入输出文件 outfile.write(iv) # 逐块读取输入文件,并加密后写入输出文件 while True: chunk = infile.read(chunksize) if len(chunk) == 0: break elif len(chunk) % AES.block_size != 0: # 如果长度不是16的倍数,则使用PKCS7填充 chunk += b' ' * (AES.block_size - len(chunk) % AES.block_size) outfile.write(cipher.encrypt(chunk)) # 定义解密函数 def decrypt_file(key, in_filename, out_filename=None, chunksize=24*1024): # 如果没有指定输出文件名,则将输入文件名去掉'.enc'后缀作为输出文件名 if not out_filename: out_filename = in_filename[:-4] # 使用AES加密算法,ECB模式,PKCS7填充方式 cipher = AES.new(key, AES.MODE_ECB) # 打开输入文件和输出文件 with open(in_filename, 'rb') as infile: with open(out_filename, 'wb') as outfile: # 读取IV向量 iv = infile.read(AES.block_size) # 逐块读取输入文件,并解密后写入输出文件 while True: chunk = infile.read(chunksize) if len(chunk) == 0: break outfile.write(cipher.decrypt(chunk)) # 去掉PKCS7填充 outfile.truncate(outfile.tell() - ord(outfile.read()[-1])) ``` 使用以上代码,你可以调用`encrypt_file()`函数来加密文件,调用`decrypt_file()`函数来解密加密后的文件。这里需要传入一个`key`参数,作为加密和解密的密钥。注意,密钥长度必须是16、24或32字节(即128、192或256位)。 例如,你可以这样来加密一个文件: ```python key = b'your_secret_key' # 定义密钥 encrypt_file(key, 'plain_file.txt', 'encrypted_file.txt.enc') # 加密文件 ``` 然后,你可以这样来解密加密后的文件: ```python key = b'your_secret_key' # 定义密钥 decrypt_file(key, 'encrypted_file.txt.enc', 'decrypted_file.txt') # 解密文件 ``` 以上代码中的加密算法使用了AES,ECB模式和PKCS7填充方式。在实际使用中,你应该根据自己的需求选择合适的加密算法、加密模式和填充方式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

学习&实践爱好者

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值