Python中Cryptography库实现加密解密

 更新时间:2024年02月03日 11:04:05   作者:软件技术爱好者  
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

示例

1、生成私钥和获取公钥

# -*- coding: utf-8 -*-

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

# 生成私钥
private_key = rsa.generate_private_key(
    public_exponent=65537,
    key_size=2048,
    backend=default_backend()
)

# 获取公钥
public_key = private_key.public_key()

2、私钥和公钥序列化

# 私钥序列化
private_key_pem = private_key.private_bytes(
    encoding=serialization.Encoding.PEM,
    format=serialization.PrivateFormat.PKCS8,
    encryption_algorithm=serialization.NoEncryption()
)

# 保存私钥到文件
with open('private.key', 'wb') as f:
    f.write(private_key_pem)


# 公钥序列化
public_key_pem = public_key.public_bytes(
    encoding=serialization.Encoding.PEM,
    format=serialization.PublicFormat.SubjectPublicKeyInfo
)

# 保存公钥到文件
with open('public.pem', 'wb') as f:
    f.write(public_key_pem)

3、私钥和公钥的反序列化

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization

# 从文件加载私钥
with open("private.key", "rb") as private_key_file:
    private_key = serialization.load_pem_private_key(
        private_key_file.read(),
        password=None,
        backend=default_backend()
    )

# 从文件加载公钥
with open("public.pem", "rb") as public_pem_file:
    public_key = serialization.load_pem_public_key(
        public_pem_file.read(),
        backend=default_backend()
    )

4、公钥加密私钥解密

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

# 公钥解密
message = 'Hello'

encrypted = public_key.encrypt(
    plaintext=message.encode('utf-8'),
    padding=padding.OAEP(
        mgf=padding.MGF1(algorithm=hashes.SHA256()),
        algorithm=hashes.SHA256(),
        label=None
    )
)

print(encrypted)
# b'm\xf2\x8d\xa84\xbe\x13\xe1...'

# 私钥解密
original_message = private_key.decrypt(
    ciphertext=encrypted,
    padding=padding.OAEP(
        mgf=padding.MGF1(algorithm=hashes.SHA256()),
        algorithm=hashes.SHA256(),
        label=None
    )
)

print(original_message.decode('utf-8'))
# Hello

5、私钥签名公钥验签

# -*- coding: utf-8 -*-

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

# 私钥签名
message = 'Hello'

signature = private_key.sign(
    data=message.encode('utf-8'),
    padding=padding.PSS(
        mgf=padding.MGF1(hashes.SHA256()),
        salt_length=padding.PSS.MAX_LENGTH
    ),
    algorithm=hashes.SHA256()
)
print(signature)
# b'm\xf2\x8d\xa84\xbe\x13\xe1...'

# 公钥验签 如果验证失败抛出异常cryptography.exceptions.InvalidSignature
public_key.verify(
    signature=signature,
    data='Hello'.encode('utf-8'),
    padding=padding.PSS(
        mgf=padding.MGF1(hashes.SHA256()),
        salt_length=padding.PSS.MAX_LENGTH
    ),
    algorithm=hashes.SHA256()
)

简单示例:使用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哈希算法一起使用,以确保加密过程的安全性。

到此这篇关于Python中Cryptography库实现加密解密的文章就介绍到这了,更多相关Python Cryptography加密解密内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

最新评论