尝试了上面的所有内容以及其他线程的更多内容,这对我有用,相当于 openssl 中的内容:
不是最好的 encrpython 但那些是要求
解密:openssl enc -d -aes256 -md md5 -in {->path_in} -out {->path_out} -pass pass:{->pass}
加密:openssl enc -e -aes256 -md md5 -in {->path_in} -out {->path_out} -pass pass:{->pass}
Python:
from os import urandom
from hashlib import md5
from Crypto.Cipher import AES
import typer
def filecrypto(in_file, out_file, password, decrypt: bool = True):
salt_header = 'Salted__'
def derive_key_and_iv(password, salt, key_length, iv_length):
d = d_i = b'' # changed '' to b''
while len(d) < key_length + iv_length:
# changed password to str.encode(password)
d_i = md5(d_i + str.encode(password) + salt).digest()
d += d_i
return d[:key_length], d[key_length:key_length+iv_length]
def encrypt_f(in_file, out_file, password, salt_header=salt_header, key_length=32):
bs = AES.block_size
salt = urandom(bs - len(salt_header))
key, iv = derive_key_and_iv(password, salt, key_length, bs)
cipher = AES.new(key, AES.MODE_CBC, iv)
with open(out_file, 'wb') as f_out:
# write the first line or the salted header
f_out.write(str.encode(salt_header) + salt)
with open(in_file, 'rb') as f_in:
f_out.write(cipher.encrypt(f_in.read()))
def decrypt_f(in_file, out_file, password, salt_header=salt_header, key_length=32):
bs = AES.block_size
with open(in_file, 'rb') as f_in:
# retrieve the salted header
salt = f_in.read(bs)[len(salt_header):]
key, iv = derive_key_and_iv(password, salt, key_length, bs)
cipher = AES.new(key, AES.MODE_CBC, iv)
with open(out_file, 'wb') as f_out:
f_out.write(cipher.decrypt(f_in.read()))
return decrypt_f(in_file, out_file, password) if decrypt else encrypt_f(in_file, out_file, password)
if __name__ == "__filecrypto__":
typer.run(filecrypto)