在这里的第一篇文章,为了不浪费你的时间,让我们直接进入它:是否可以为 cryptography.fernet 模块生成的密钥指定一个早期定义的变量名称?例子:
# import required module
import os
from cryptography.fernet import Fernet
from tkinter import *
from tkinter.filedialog import askopenfilename
Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing
filepath = askopenfilename() # show an "Open" dialog box and return the path to the selected file
var1 = (os.path.basename(filepath)) # cuts the filepath into a filename
# key generation
key = Fernet.generate_key()
# string the key in a file
with open('filekey.key','wb') as filekey:
filekey.write(key)
# opening key
with open('filekey.key', 'rb') as filekey:
key = filekey.read()
# using the generated key
fernet = Fernet(key)
# opening the original file to encrypt
with open(filepath, 'rb') as file:
original = file.read()
# encrypting the file
encrypted = fernet.encrypt(original)
# opening the file in write mode and
# writing the encrypted data
with open(filepath, 'wb') as encrypted_file:
encrypted_file.write(encrypted)
我的目标是为生成的密钥提供 var1 变量的输出作为名称。