【发布时间】:2014-06-13 12:00:20
【问题描述】:
我有一个正在使用跨平台的加密/解密类。我在服务器和客户端上使用相同的类。我在 Linux 服务器上加密文件,然后在 Linux 或 Windows 客户端上解密。我在 Linux 上解密时没有问题,但是当我将文件传输到 Windows 并尝试解密时,出现以下异常:
ValueError: 输入字符串的长度必须是 16 的倍数
我的第一个想法是它是由不同的文件系统以及用于创建填充的任何字符引起的。这是我的课程代码:
class FileSec:
def __init__(self):
# File chunk size
self.chunk_size = 64*1024
# Encrypt file with OpenSSL
def encrypt(self, infile, outfile, key):
if not infile or not os.path.isfile(infile):
return False
if not outfile or os.path.isfile(outfile):
return False
if not key:
return False
# Encrypt the file
iv = ''.join(chr(random.randint(0, 0xFF)) for i in range(16))
encryptor = AES.new(key, AES.MODE_CBC, iv)
filesize = os.path.getsize(infile)
with open(infile, 'rb') as ifh:
with open(outfile, 'wb') as ofh:
ofh.write(struct.pack('<Q', filesize))
ofh.write(iv)
while True:
chunk = ifh.read(self.chunk_size)
if len(chunk) == 0:
break
elif len(chunk) % 16 != 0:
chunk += ' ' * (16 - len(chunk) % 16)
ofh.write(encryptor.encrypt(chunk))
return True
# Decrypt file with OpenSSL
def decrypt(self, infile, outfile, key):
if not infile or not os.path.isfile(infile):
return False
if not outfile or os.path.isfile(outfile):
return False
if not key:
return False
# Decrypt the file
with open(infile, 'rb') as ifh:
origsize = struct.unpack('<Q', ifh.read(struct.calcsize('Q')))[0]
iv = ifh.read(16)
decryptor = AES.new(key, AES.MODE_CBC, iv)
with open(outfile, 'wb') as ofh:
while True:
chunk = ifh.read(self.chunk_size)
if len(chunk) == 0:
break
ofh.write(decryptor.decrypt(chunk))
ofh.truncate(origsize)
return True
我正在使用从这里改编的代码:http://eli.thegreenplace.net/2010/06/25/aes-encryption-of-files-in-python-with-pycrypto/
有人对我如何修改这个类以跨平台工作有任何建议吗?
【问题讨论】:
-
OT:
return False有什么用,而不是抛出异常,顺便说一句?
标签: python linux windows encryption pycrypto