我现在想出了如何加密单个文件。现在,我希望能够加密目录中的所有文本文件和文档。我遇到了以下问题,我分配了一个变量,但是我的终端上写着:
UnboundLocalError:赋值前引用的局部变量'enc‘。
我不知道怎么解决这个问题。我试过将变量设置为全局变量,但它不起作用。
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()发布于 2019-03-01 09:30:58
我认为你错过了你的缩进,你应该尝试像这样的东西把你的写在你的if块中
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()https://stackoverflow.com/questions/54941525
复制相似问题