我遇到了解密文本文件的问题,说“我想成为明文”。
加密是一项很好的工作,但是当我解密时,它会混合,清除文本并加密数据。
现在我知道我的写作有点业余..但我需要你的帮助来完成它。 我尝试在def函数中构建它,但它没有顺利进行..
我认为加密中的填充是问题所在,但是当我在一个16字节的文本文件上测试它时,它仍然是混合的。
#!/usr/bin/env python
from Crypto.Cipher import AES
from Crypto.Protocol.KDF import PBKDF2
from Crypto import Random
import os
file_path = raw_input("Enter File path: ")
if os.path.isdir(file_path): #check if the path exists
print "\nFile path founded, continue..\n"
else:
print "\nFile path is not correct\nExiting.\n"
exit(0)
file_name = raw_input("Enter File name: ")
full_path = file_path + file_name
if os.path.isfile(full_path):
print "\nFile name founded, continue..\n"
else:
print "\nFile name is not correct\nExiting.\n"
exit(0)
print "Now encrypt"
key_size = 32 #AES256
iterations = 10000
key = os.urandom(32)
read = open(full_path,'r+')
line = read.readline()
secret = line
length = 16 - (len(secret) % 16) #PKCS7 adds bytes of the length of padding
secret += chr(length) * length
read.close()
salt = Random.new().read(key_size) #salt the hash
iv = Random.new().read(AES.block_size)
derived_key = PBKDF2(key, salt, key_size, iterations)
cipher = AES.new(derived_key, AES.MODE_CBC, iv)
encodedtext = iv + cipher.encrypt(secret)
read = open(full_path, 'w')
read.write(encodedtext)
read.close()
print "Now decrypt"
key_size2 = 32 #AES256
iterations2 = 10000
read2 = open(full_path,'r')
line2 = read2.readline()
secret2 = line2
length2 = 16 - (len(secret2) % 16) #PKCS7 adds bytes of the length of padding
secret2 += chr(length2) * length2
read2.close()
dencodedtext2 = iv + cipher.decrypt(secret2)
read2 = open(full_path, 'w')
read2.write(dencodedtext2)
read2.close()
print "that worked?"
进行测试 我给了一条路'/ home / **** / Dekstop / 我给文件'test.txt'文本'我想要是明文文件' 我得到了这个,
悑晍㱣弧歼턕컫聅㇛좎䀋伧粁粁粁粁粁粁粁粁粁粁粁粁粁ꂛꂛꂛꂛꂛꂛꂛꂛꂛꂛꂛꂛꂛꂛꂛꂛꂛꂛꂛꂛꂛꂛ
为什么当我在'dencodedtext2 = iv + cipher.decrypt(secret2)'后打印secret2时,文本与加密混合? 我怎么能修好它? 我真是太可怕了?
感谢任何人的帮助!
答案 0 :(得分:1)
代码中有两个主要错误: