繁体   English   中英

使用 cryptography.fernet 解密多个文件

[英]Decrypting multiple files using cryptography.fernet

我正在尝试编写一个代码,我可以在其中一次从子目录中解密多条消息。

我创建了一个密钥目录和一个消息目录。 密钥目录包含包含解密密钥的.key 文件的子目录。

消息目录包含包含加密消息的.key 文件的子目录。

当我选择一个子目录时,我希望代码解密该子目录中的所有消息。 目前它只解密所选子目录的一个文件。 密钥和加密文件具有相同的名称。

谁能帮我这个? - 初学者新手程序员

from cryptography.fernet import Fernet
import os
import glob

mainfolderlocation = os.path.dirname(os.path.abspath(__file__))
keyfolderlocation = mainfolderlocation+'\Keys'
messagefolderlocation = mainfolderlocation+'\Messages' 

folder = input('Choose folder:\n')
            try:
                os.chdir(messagefolderlocation+'\{}'.format(folder))
                for file in glob.glob('*.key'):
                    filem = open(file, 'rb')
                    encrypted = filem.read()
                    filem.close()
                    filename= os.path.splitext(file)[0]

                os.chdir(keyfolderlocation+'\{}'.format(folder))    
                for file in glob.glob(filename+'.key'):
                    filek = open(file, 'rb')
                    key = filek.read()
                    filek.close()

                    f = Fernet(key)
                    decrypted = f.decrypt(encrypted)
                    decode=decrypted.decode('utf-8')           
                    print(decode)

            except:
                print('\nThis folder does not exist!')

你的问题似乎是你的循环有错误。 我对 glob 没有太多经验,但您可能想尝试这样的事情:

from cryptography.fernet import Fernet
import os
import glob

mainfolderlocation = os.path.dirname(os.path.abspath(__file__))
keyfolderlocation = mainfolderlocation+'\Keys'
messagefolderlocation = mainfolderlocation+'\Messages' 

files = []

folder = input('Choose folder:\n')
os.chdir(keyfolderlocation+'\{}'.format(folder))    
for file in glob.glob(file+'.key'):
    filek = open(file, 'rb')
    key = filek.read()
    filek.close()

if os.path.exists(folder):
    for r, d, f in os.walk(folder):
        for file in f:
            if '.key' in file:
                files.append(os.path.join(r, file))
else:
    print('\nThis folder does not exist!')

for i in files:
    try:
        filem = open(i, 'rb')
        encrypted = filem.read()
        filem.close()
        filename= os.path.splitext(i)[0]



        f = Fernet(key)
        decrypted = f.decrypt(encrypted)
        decode=decrypted.decode('utf-8')           
        print(decode)

    except:
        print('\nThis folder does not exist!') 

所以基本上发生的事情是你抓住你的钥匙是什么(注意目前如果你有多个.key文件你会遇到问题),列出文件夹目录中的所有文件(如果存在),然后为每个文件您打开它,阅读内容,解密并打印这些文件。 我没有机会测试它。

您可能还想考虑将您的解密放入 function 并在每个文件上调用它,而不是让它成为整体,但这只是一种风格选择。 此外,我将密钥抓取放在 try 块上方,因为您只想抓取一次密钥,否则您将浪费性能将变量设置为相同的值。 除非您为每个文件使用不同的密钥文件,在这种情况下,您可能希望为每一对制作字典,因此“bananasandwich.txt”对应于“bananasandwich.key”。 祝你好运!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM