So entschlüsseln Sie eine OpenSSL-verschlüsselte Datei mit Python3.
Es ist eine Situation, die ziemlich wahrscheinlich erscheint, aber wenn es um das Entschlüsseln und Verschlüsseln von Dateien geht, gibt es nur wenige Dokumente und ich hatte ein kleines Problem, also habe ich mir eine Notiz gemacht.
Die Entwicklungsumgebung ist wie folgt. ・ Python 3.7.3 ・ Windows10 ・ Installieren Sie die erforderlichen Pakete jederzeit mit pip install
import binascii
import io
from hashlib import sha256
from Crypto.Cipher import AES
from Crypto import Random
@classmethod
def decrypt(self,infile, expf, key_length=32):
"""
Decrypt the file.
Parameters
----------
infile : string
File path before decryption
expf : string
File path after decryption
key_length : int
key_length
Returns
None
-------
"""
# Divide password hashed by sha256 to first half and second half ,set to key and iv. This is OpenSSL specifications.
key = binascii.unhexlify('E1B85B27D6BCB05846C18E6A48F118E8')
iv = binascii.unhexlify('9F0C0587140DE9FB3359F8370D0DBA08')
in_file = open( infile , 'rb' )
out_file = open( expf , 'wb' )
bs = AES.block_size
cipher = AES.new(self.key, AES.MODE_CBC, self.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 = chunk[-1]
chunk = chunk[:-padding_length]
finished = True
if type(chunk) is str:
wk = chunk.encode('utf-8')
elif type(chunk) is bytes:
wk = chunk
else:
wk = chunk
out_file.write(wk)
# file close
in_file.close()
out_file.close()
@classmethod
def encrypt(self,in_file, out_file, key_length=32):
"""
Encrypt the file.
Parameters
----------
in_file : string
File path before encryption
out_file : string
File path before encryption
key_length : int
key_length
Returns
None
-------
"""
# Divide password hashed by sha256 to first half and second half ,set to key and iv. This is OpenSSL specifications.
key = binascii.unhexlify('E1B85B27D6BCB05846C18E6A48F118E8')
iv = binascii.unhexlify('9F0C0587140DE9FB3359F8370D0DBA08')
in_file = open( in_file , 'rb' )
out_file = open( out_file , 'wb' )
bs = AES.block_size
cipher = AES.new(self.key, AES.MODE_CBC, self.iv)
finished = False
while not finished:
chunk = in_file.read(1024 * bs)
if len(chunk) == 0 or len(chunk) % bs != 0:
padding_length = (bs - len(chunk) % bs) or bs
chunk += padding_length * bytes([padding_length])
finished = True
out_file.write(cipher.encrypt(chunk))
# file close
in_file.close()
out_file.close()
Recommended Posts