LoginSignup
3
3

More than 3 years have passed since last update.

Python3でOpenSSLで暗号化したファイルを復号する

Posted at

Python3を使ってOpenSSLで暗号化したファイルを復号する方法。

結構ありそうなシチュエーションだけど、ファイルの復号・暗号となると文献が少なくちょっと苦労したのでメモ。

開発環境は以下。
・Python3.7.3
・Windows10
・必要なパッケージは随時 pip install で入れる

importはこんな感じに書く。(あくまで例)

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

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





こんどは暗号化。

ファイルを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()
3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3