首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >我已经分配了变量,但是输出说:“赋值前引用的局部变量”

我已经分配了变量,但是输出说:“赋值前引用的局部变量”
EN

Stack Overflow用户
提问于 2019-03-01 09:23:57
回答 1查看 198关注 0票数 0

我现在想出了如何加密单个文件。现在,我希望能够加密目录中的所有文本文件和文档。我遇到了以下问题,我分配了一个变量,但是我的终端上写着:

UnboundLocalError:赋值前引用的局部变量'enc‘。

我不知道怎么解决这个问题。我试过将变量设置为全局变量,但它不起作用。

代码语言:javascript
运行
复制
import os
from Crypto import Random
from Crypto.Cipher import AES

extensions = ['docs', 'txt']

tree = '.'

def padding(s):
   return s + b"\0" * (AES.block_size - len(s) % AES.block_size)

def encrypt(message, key, key_size=256):
   message = padding(message)
   iv = Random.new().read(AES.block_size)
   cipher = AES.new(key, AES.MODE_CBC, iv)
   return iv + cipher.encrypt(message)

def allfiles():
   for root, dirs, files in os.walk(tree):
       for file in files:
       if (file.endswith(tuple(extensions))):
            with open(file, 'rb') as fs:
                plaintext = fs.read()
                enc = encrypt(plaintext, key)
       with open(file, 'w') as fs:
            fs.write(enc)

       key = b'\xbf\xc0\x85)\x10nc\x94\x02)j\xdf\xcb\xc4\x94\x9d(\x9e[EX\xc8\xd5\xbfI{\xa2$\x05(\xd5\x18'


allfiles()
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-03-01 09:30:58

我认为你错过了你的缩进,你应该尝试像这样的东西把你的写在你的if块中

代码语言:javascript
运行
复制
import os
from Crypto import Random
from Crypto.Cipher import AES

extensions = ['docs', 'txt']

tree = '.'

def padding(s):
   return s + b"\0" * (AES.block_size - len(s) % AES.block_size)

def encrypt(message, key, key_size=256):
   message = padding(message)
   iv = Random.new().read(AES.block_size)
   cipher = AES.new(key, AES.MODE_CBC, iv)
   return iv + cipher.encrypt(message)

def allfiles():
   for root, dirs, files in os.walk(tree):
       for file in files:
       if (file.endswith(tuple(extensions))):
            with open(file, 'rb') as fs:
                plaintext = fs.read()
                enc = encrypt(plaintext, key)
            with open(file, 'w') as fs:
                fs.write(enc) # Here enc is defined in your if bloc for sure

            key = b'\xbf\xc0\x85)\x10nc\x94\x02)j\xdf\xcb\xc4\x94\x9d(\x9e[EX\xc8\xd5\xbfI{\xa2$\x05(\xd5\x18'
       else:
            print('file not encrypted') # enc is not defined


allfiles()
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54941525

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档