外贸网站推广建站,网络公司排名100名,seo网页优化培训,织梦个人网站用Python和 Cryptography库给你的文件加密解密
用Python和 Cryptography库给你的文件加把安全锁。
先介绍与加密解密有关的几个基本概念。
加密#xff08;Encryption#xff09;#xff1a;加密是将明文转换为密文的过程#xff0c;使得未经授权的人无法读懂。
解密Encryption加密是将明文转换为密文的过程使得未经授权的人无法读懂。
解密Decryption解密是将密文转换为明文的过程使得原始信息可以被正确的人阅读。
密钥Key密钥是加密和解密过程中的关键。它可以是单个数字、字符串或者是更复杂的密钥对象。
算法算法是加密和解密过程中的具体步骤。
cryptography是一个强大的Python库提供了一套丰富的加密相关的操作用于安全地处理数据。它旨在提供简单易用的加密方法同时也支持更高级的加密需求使这项技术变得易于使用。cryptography库包含两个主要的高级组件Fernet对称加密和hazmat危险材料层。
主要特点
易用性cryptography库的设计初衷是易于使用尽量减少安全漏洞的出现。
安全性它提供了最新的加密算法并且经过安全专家的审查。
灵活性对于需要直接访问加密算法的高级用户cryptography提供了hazmat模块。
主要组件
Fernet提供了对称加密的实现非常适合用于加密和解密可以安全共享密钥的场景。使用Fernet非常简单只需要一个密钥就可以进行安全的数据加密和解密。
hazmatHazardous 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 bHello, cryptography!
encrypted_data cipher_suite.encrypt(data)
print(fEncrypted: {encrypted_data})# 解密数据
decrypted_data cipher_suite.decrypt(encrypted_data)
print(fDecrypted: {decrypted_data})运行效果 图形用户界面的文件加密解密程序
使用tkinter添加界面的加密解密程序当用户点击“加密文件”或“解密文件”按钮时程序会从这个文本框中获取密钥并使用它进行相应的加密或解密操作。加密和解密的文件将会被保存在与原文件相同的目录下加密文件的文件名在原图片文件名前添加enc_解密文件的文件名在原加密图片文件名前添加dec_
先给出运行效果 源码如下
import tkinter as tk
from tkinter import filedialog
from cryptography.fernet import Fernet
import osdef 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 fenc_{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(textf提示文件已加密{encrypted_filename})except Exception as e:status_label.config(textf提示加密失败: {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 fdec_{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(textf提示文件已解密{decrypted_filename})except Exception as e:status_label.config(textf提示解密失败: {str(e)})# 创建GUI界面
def select_file(operation, key_entry, status_label):key key_entry.get() # 从文本框获取密钥if not key:status_label.config(text提示操作失败未输入密钥)returnfile_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*, width50) # 密钥输入框key_entry.insert(0, X3Q8PvDs2EzKHK-8TjgUE8HkZ8QeuOe0S7-3VVqjTDI) # 设置默认值 key_entry.pack()status_label tk.Label(root, text提示请选择操作, height2)status_label.pack()tk.Button(root, text加密文件, commandlambda: select_file(encrypt, key_entry, status_label)).pack()tk.Button(root, text解密文件, commandlambda: 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_exponent65537,key_size2048,backenddefault_backend()
)
public_key private_key.public_key()# 将私钥序列化并保存到文件
with open(private_key.pem, wb) as f:f.write(private_key.private_bytes(encodingserialization.Encoding.PEM,formatserialization.PrivateFormat.PKCS8,encryption_algorithmserialization.NoEncryption()))# 将公钥序列化并保存到文件
with open(public_key.pem, wb) as f:f.write(public_key.public_bytes(encodingserialization.Encoding.PEM,formatserialization.PublicFormat.SubjectPublicKeyInfo))# 读取公钥进行加密
with open(public_key.pem, rb) as f:public_key serialization.load_pem_public_key(f.read(),backenddefault_backend())message Hello, RSA Cryptography!.encode()
encrypted public_key.encrypt(message,padding.OAEP(mgfpadding.MGF1(algorithmhashes.SHA256()),algorithmhashes.SHA256(),labelNone)
)# 读取私钥进行解密
with open(private_key.pem, rb) as f:private_key serialization.load_pem_private_key(f.read(),passwordNone,backenddefault_backend())original_message private_key.decrypt(encrypted,padding.OAEP(mgfpadding.MGF1(algorithmhashes.SHA256()),algorithmhashes.SHA256(),labelNone)
)# 显示解密后的消息
print(original_message.decode())这个例子首先生成了一个2048位的RSA密钥对将私钥保存到private_key.pem文件中将公钥保存到public_key.pem文件中。接下来代码从public_key.pem文件中读取公钥用于加密消息从private_key.pem文件中读取私钥用于解密消息。最后使用公钥对一段消息进行加密然后使用私钥将消息解密。padding.OAEP是一种常用的填充方式与SHA-256哈希算法一起使用以确保加密过程的安全性。 OK!