How to decrypt a file encrypted with OpenSSL using Python3.
It's a situation that seems quite likely, but when it comes to decrypting and encrypting files, there aren't many documents, so I made a note.
The development environment is as follows. ・ Python 3.7.3 ・ Windows 10 ・ Install necessary packages with pip install at any time.
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