这段代码有多安全?可以在没有密码的情况下解密文本/文件吗?
from Crypto.Cipher import AES
from Crypto import Random
import hashlib
import base64
import os
import struct
BS = 16
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS).encode()
unpad = lambda s: s[:-ord(s[len(s)-1:])]
class AESCipher(object):
def __init__(self, key, salt):
self.key = hashlib.pbkdf2_hmac('sha256', key.encode(), salt.encode(), 100000)
def encrypt(self, plaintext):
plaintext = pad(plaintext.encode())
iv = Random.new().read(BS)
cipher = AES.new(key=self.key, mode=AES.MODE_CBC, iv=iv)
enc = cipher.encrypt(plaintext)
return base64.b64encode(iv + enc).decode()
def decrypt(self, enc):
enc = base64.b64decode(enc)
iv = enc[:BS]
enc = enc[BS:]
cipher = AES.new(key=self.key, mode=AES.MODE_CBC, iv=iv)
plaintext = cipher.decrypt(enc)
return unpad(plaintext).decode()
def encrypt_file(self, in_file_name, out_file_name=None, chunk_size=1024 * 64):
if not out_file_name:
out_file_name = in_file_name + '.enc'
iv = Random.new().read(BS)
cipher = AES.new(key=self.key, mode=AES.MODE_CBC, iv=iv)
file_size = os.path.getsize(in_file_name)
with open(in_file_name, 'rb') as in_file:
with open(out_file_name, 'wb') as out_file:
out_file.write(struct.pack('<Q', file_size))
out_file.write(iv)
while True:
chunk = in_file.read(chunk_size)
if len(chunk) == 0:
break
elif len(chunk) % 16 != 0:
chunk += b' ' * (16 - len(chunk) % 16)
out_file.write(cipher.encrypt(chunk))
def decrypt_file(self, in_file_name, out_file_name=None, chunk_size=1024 * 64):
if not out_file_name:
out_file_name = os.path.splitext(in_file_name)[0]
if out_file_name == in_file_name:
out_file_name += '.decrypted'
with open(in_file_name, 'rb') as in_file:
with open(out_file_name, 'wb') as out_file:
orig_size = struct.unpack('<Q', in_file.read(struct.calcsize('Q')))[0]
iv = in_file.read(16)
cipher = AES.new(key=self.key, mode=AES.MODE_CBC, iv=iv)
while True:
chunk = in_file.read(chunk_size)
if len(chunk) == 0:
break
out_file.write(cipher.decrypt(chunk))
out_file.truncate(orig_size)
我可以使用此脚本加密我的数据吗?我使用hashlib来派生密钥,也许我应该使用pyCrypto中的密钥派生函数?