用python加密文件与解密文件

测试环境:python3.12.6(可以不用)

目录:

        前言:

加密方式:

        对称加密(Symmetric Encryption)

        非对称加密(Asymmetric Encryption)

加密方式的实际用例:

Fernet(对称加密)

创建秘钥:

加密文件:

读取秘钥:

读取文件与加密文件:

解密文件:

运行示例:

AES(对称加密)

创建秘钥:

加密文件:

读取秘钥:

读取文件与加密文件:

解密文件:

运行示例:

RSA(非对称加密)

        一般与Hash算法并用,形成数字签名:

发送后验证:

加密 :

创建秘钥:

加密信息:

 解密:

运行示例:


前言:

在生活中,文件的加密是很重要的,如果不加密文件,要是被黑客盗取了,信息是明文的,很容易被泄露

cryptography是一个很好的python加密包,cryptography是第三方包,所以要导入:

pip install cryptography

或者用国内镜像源:

pip install --user cryptography -i https://pypi.tuna.tsinghua.edu.cn/simple

加密方式:

         对称加密可加密任何文件(如*.exe,*.mp3等)

        对称加密(Symmetric Encryption)

          //生成一个秘钥,同过秘钥来进行加密/解密

                  优点:速度快,效率高,占用的计算资源更少

                  缺点:风险高,密钥管理难

                Fernet(对称加密)

                AES(对称加密)

        非对称加密(Asymmetric Encryption)

                  优点:风险低,秘钥分享风险较低

                  缺点:速度慢,占用的计算资源更多

                RSA(非对称加密)

在数据多、不分享文件秘钥的情况下可以用对称加密

加密方式的实际用例:

Fernet(对称加密)

最简单的加密方式(适合新手)

创建秘钥:

from cryptography.fernet import Fernet  

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

#cipher_suite = Fernet.generate_key() #这一种也可以

with open('secret.key', 'wb') as key_file:
    key_file.write(cipher_suite)

加密文件:

读取秘钥:
file=input("输入加密文件:")
# 读取密钥(需先创建)
with open('secret.key', 'rb') as key_file:
    key = key_file.read()
读取文件与加密文件:
from cryptography.fernet import Fernet
# 初始化加密器
cipher = Fernet(key)
# 加密文件
with open(file, 'rb') as file:
    file_new = file.read()

# 加密内容
new_data = cipher.encrypt(file_new)

# 将加密后的内容写入文件
with open(file, 'wb') as new_file:
    new_file.write(new_data)

解密文件:

  如果有多重加密一键解密

from cryptography.fernet import Fernet
import tkinter as tk
from tkinter import messagebox as me
from tkinter import filedialog as fi

win = tk.Tk()
win.geometry("200x180")
win.title("解密")
c=0
def jm():
    k=0
    global c
    if c==0:
        f = fi.askopenfilename(title="解密文件:")
    try:
        with open('secret.key', 'rb') as key_file:
            key = key_file.read()

        # 初始化解密器
        cipher = Fernet(key)

        # 读取加密文件
        with open(f, 'rb') as new_file:
            new_data = new_file.read()

        # 解密内容
        decry_data = cipher.decrypt(new_data)

        # 将解密后的内容写入新文件
        with open(f, 'wb') as decry_file:
            decrypted_file.write(decry_data)
        c+=1
    except:
        k=1
        pass
    if k==0:
        jm()


but = tk.Button(win, text="解密", font=("楷体", 30), command=jm)
but.place(x=45, y=90)
win.mainloop()

运行示例:

秘钥:UaelSzFLKxgUG9O0wA0z2dwnZ3UVNuO95TWqChqhDbU=

明文:baoyushuoBYsuu

密文由于过多,在此无法展示(如果想了解,可在置顶链接下载)

        缺点:占用空间大

AES(对称加密)

Fernet相对难的多,秘钥不容易懂

创建秘钥:

import os
# 生成一个新的密钥  
key = os.urandom(32)  # AES-256  
# 将密钥保存到文件  
with open("secret.key", 'wb') as key_file:  
    key_file.write(key)   

加密文件:

读取秘钥:
with open("secret.key", 'rb') as key_file:  
    key = key_file.read()  
读取文件与加密文件:
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
import os

f=input("输入加密文件:")
with open(f, 'rb') as file:
    plain_text = file.read()

iv = os.urandom(16)  # 生成随机IV
cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())
encryptor = cipher.encryptor()

# 填充明文以符合块大小
padding_length = 16 - len(plain_text) % 16
padded_plain_text = plain_text + bytes([padding_length]) * padding_length

encrypted_data = encryptor.update(padded_plain_text) + encryptor.finalize()

with open(f, 'wb') as key_file:
    key_file.write(iv)

with open(f, 'ab') as key_file:
    key_file.write(encrypted_data)

解密文件:

from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
import os
with open("secret.key", 'rb') as key_file:
    key = key_file.read()
f=input("输入解密文件:")
with open(f, 'rb') as file:
    encrypted_data= file.read()

iv = encrypted_data[:16]  # 提取IV
encrypted_data = encrypted_data[16:]  # 提取加密数据
cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())
decryptor = cipher.decryptor()

padded_plain_text = decryptor.update(encrypted_data) + decryptor.finalize()

# 去掉填充
padding_length = padded_plain_text[-1]
v=padded_plain_text[:-padding_length]

with open(f, 'wb') as key_file:
    key_file.write(v)

运行示例:

秘钥:尚]ッp9涞鋢盈Bf?]q焆JM嵿O紽+ 

明文:baoyushuoBYsuu

密文:E瑊efQuq5H?妸蟳 p膦SKU愗⒘A0?

        优点:秘钥比Fernet更难读取,安全度更高,密文占用空间更小

RSA(非对称加密)

        难度较高,适合加密需发送的重要代码,速度慢,只能加密文字,不能加密文件,一般用于发送对称加密秘钥

RSA加密传输方式

        一般与Hash算法并用,形成数字签名:

 注:CA是信息公证处

发送后验证:

加密 :

创建秘钥:
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import serialization, hashes

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

public_key = private_key.public_key()

# 将私钥保存到文件
private_key_path = 'private_key.pem'
with open(private_key_path, 'wb') as private_key_file:
    private_key_file.write(
        private_key.private_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PrivateFormat.TraditionalOpenSSL,
            encryption_algorithm=serialization.NoEncryption()  # 不加密
        )
    )

# 将公钥保存到文件
public_key_path = 'public_key.pem'
with open(public_key_path, 'wb') as public_key_file:
    public_key_file.write(
        public_key.public_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PublicFormat.SubjectPublicKeyInfo,
        )
    )


加密信息:
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import  padding
from cryptography.hazmat.primitives import serialization, hashes

# 读取私钥
private_key_path = 'private_key.pem'
with open(private_key_path, 'rb') as private_key_file:
    private_key_data = private_key_file.read()

# 从 PEM 数据中加载私钥
private_key = serialization.load_pem_private_key(
    private_key_data,
    password=None,  # 如果您保存时未加密则设置为 None
    backend=default_backend()
)

# 获取公钥
public_key = private_key.public_key()
print("公钥读取完成")

# 输入要加密的文本信息
message_to_encrypt = input("请输入要加密的文本信息:").encode()

# 加密消息
encrypted_message = public_key.encrypt(
    message_to_encrypt,
    padding.OAEP(
        mgf=padding.MGF1(algorithm=hashes.SHA256()),
        algorithm=hashes.SHA256(),
        label=None
    )
)

# 保存加密后的消息到文件
encrypted_file_path = input("请输入保存加密后的文件名(包括扩展名,如encrypted.bin):")
with open(encrypted_file_path, 'wb') as v:
    v.write(encrypted_message)

print(f"加密后的消息已保存到: {encrypted_file_path}")

 解密:

from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.backends import default_backend
import os
# 读取并打印私钥
private_key_path = 'private_key.pem'
with open(private_key_path, 'rb') as private_key_file:
    private_key_data = private_key_file.read()

# 从 PEM 数据中加载私钥
private_key = serialization.load_pem_private_key(
    private_key_data,
    password=None,  # 如果您保存时未加密则设置为 None
    backend=default_backend()
)
print("私钥读取完成")
f=input("输入解密文件:")
with open(f, 'rb') as file:
    encrypted_message= file.read()

# 解密
decrypted_message = private_key.decrypt(
    encrypted_message,
    padding.OAEP(
        mgf=padding.MGF1(algorithm=hashes.SHA256()),
        algorithm=hashes.SHA256(),
        label=None
    )
)
print("解密后的消息:", decrypted_message.decode())

运行示例:

明文:baoyushuoBYsuu

密文:[肟g栻s泦I楶炚>电KQf綑接索?e桭裃堘F"=寘l?w??嬒v<昢/\独Vc z乜?.橨>?\? 鉳Aq迃霑抟溊'    繢顏 頋c斚癩|&e?鯫+1牽)?尩N辘x猱笤j枲.I%3;畧>F捶    f臸Q+???p徾;b鲢?乙蘏滊黄捫`?砓X`>l珣蘽    謯鮪<?怶H?f?疱)柃Q|nQ莓|!穗縘??

最后,大家要保护好自己的数据,防止泄露!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值