[英]Python code not stopping, getting stuck at a certain point
我已經寫了一小段代碼來加密文件並對其解密。 但是,它卡在某個地方,我認為它是在它最初解密它之后,因為它創建了加密文件,但沒有打印“ Encrypted!”。 我究竟做錯了什么? 這是循環之一嗎?
碼:
from hashlib import md5
from Crypto import Random
from Crypto.Cipher import AES
import os
from Crypto import *
def encrypt(in_file, out_file, key, iv):
bs = AES.block_size
cipher = AES.new(key, AES.MODE_CBC, iv)
finished = False
print('check001')
while not finished:
chunk = in_file.read(1024 * bs)
print('check002')
if len(chunk) == 0 or len(chunk) % bs != 0:
padding_length = bs - (len(chunk) % bs)
chunk += padding_length * chr(padding_length)
finished = True
out_file.write(cipher.encrypt(chunk))
print('check003')
def decrypt(in_file, out_file, key, iv):
bs = AES.block_size
cipher = AES.new(key, AES.MODE_CBC, iv)
next_chunk = ''
finished = False
while not finished:
chunk, next_chunk = next_chunk, cipher.decrypt(in_file.read(1024 * bs))
if len(next_chunk) == 0:
padding_length = ord(chunk[-1])
if padding_length < 1 or padding_length > bs:
raise ValueError("bad decrypt pad (%d)" % padding_length)
if chunk[-padding_length:] != (padding_length * chr(padding_length)):
raise ValueError("bad decrypt")
chunk = chunk[:-padding_length]
finished = True
out_file.write(chunk)
encFile= input('Enter the path of the file you would like to encrypt: ')
doneFile= encFile + '.enc'
unFile = encFile + '.dec'
in_file = open(encFile, 'rb')
print('check004')
out_file = open(doneFile, 'wb')
print('check005')
key = os.urandom(32)
iv = os.urandom(16)
print('check006')
encrypt(in_file, out_file, key, iv)
print('check007')
in_file.close()
out_file.close()
print('Encrypted!')
in_file = open(doneFile, 'rb')
out_file = open(unFile, 'wb')
decrypt(in_file, out_file, key, iv)
in_file.close()
out_file.close()
print('Decrypted!')
將代碼發布到問題中可能只是一個錯誤,但縮進看起來不正確:
while not finished:
chunk = in_file.read(1024 * bs)
if len(chunk) == 0 or len(chunk) % bs != 0:
padding_length = bs - (len(chunk) % bs)
chunk += padding_length * chr(padding_length)
finished = True
out_file.write(cipher.encrypt(chunk))
if語句不應縮進為:
while not finished:
chunk = in_file.read(1024 * bs)
if len(chunk) == 0 or len(chunk) % bs != 0:
padding_length = bs - (len(chunk) % bs)
chunk += padding_length * chr(padding_length)
finished = True
out_file.write(cipher.encrypt(chunk))
否則,您將永遠讀下去
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.