Decrypt files encrypted with OpenSSL with Python 3

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 is written like this. (Example)

import binascii
import io
from hashlib import sha256
from Crypto.Cipher import AES
from Crypto import Random

Decrypting files encrypted with OpenSSL

@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()


This time it's encrypted.

Encrypt files with OpenSSL


@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

Decrypt files encrypted with OpenSSL with Python 3
Decrypt files encrypted with openssl from python with openssl
Decrypt a string encrypted on iOS with Python
Sorting image files with Python (2)
Sort huge files with python
Sorting image files with Python (3)
Sorting image files with Python
Integrate PDF files with Python
Reading .txt files with Python
Recursively unzip zip files with python
Manipulating EAGLE .brd files with Python
[Python] POST wav files with requests [POST]
Decrypt OpenSSL AES-256-CBC ciphertext with PyCrypto
Handle Excel CSV files with Python
Read files in parallel with Python
[AWS] Using ini files with Lambda [Python]
Play audio files from Python with interrupts
Create and decrypt Caesar cipher with python
Reading and writing JSON files with Python
Download files on the web with Python
[Easy Python] Reading Excel files with openpyxl
Encrypt with Ruby (Rails) and decrypt with Python
Convert HEIC files to PNG files with Python
[Easy Python] Reading Excel files with pandas
FizzBuzz with Python3
Scraping with Python
Statistics with python
Scraping with Python
Twilio with Python
Integrate with Python
Play with 2016-Python
AES256 with python
Tested with Python
python starts with ()
with syntax (Python)
Bingo with python
Zundokokiyoshi with python
Excel with Python
Microcomputer with Python
Cast with python
[Python] Get the files in a folder with Python
Handle zip files with Japanese filenames in Python 3
Drag and drop local files with Selenium (Python)
Character encoding when dealing with files in Python 3
Download and import files with Splunk external python
Upload files to Google Drive with Lambda (Python)
Reading and writing fits files with Python (memo)
Convert multiple proto files at once with python
Read wav files with only Python standard packages
Serial communication with Python
Django 1.11 started with Python3.6
Primality test with Python
Python with eclipse + PyDev.
Socket communication with Python
Data analysis with python 2
Upload files with Django
Scraping with Python (preparation)
Try scraping with Python.
Extract the table of image files with OneDrive & Python
Learning Python with ChemTHEATER 03
"Object-oriented" learning with python