我现在想出了如何加密单个文件。现在,我希望能够加密目录中的所有文本文件和文档。我遇到以下问题,我已经分配了一个变量,但是我的终端说:
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()
答案 0 :(得分:0)
我认为您错过了缩进,应该尝试使用类似的方法将您的文字放入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()