🐙

Pythonで簡単な暗号化/復号を行うクラス

2023/03/28に公開

クラスファイル

from base64 import b64encode
import csv
from tempfile import TemporaryFile

from cryptography.fernet import Fernet # pip install cryptography

# TODO: PyArmorでコード自体を暗号化する
# https://kyogom.com/tech/pyarmor/
class Encryption:
    # 暗号化の参考ページ
    # https://laboratory.kazuuu.net/encrypting-and-decrypting-files-using-cryptography-in-python/
    def __init__(self):
        encryption_key = b"12345678901234567890123456789012" # PyArmorの恩恵が特に強い部分
        self.fernet = Fernet(b64encode(encryption_key))
    
    def write(self, file_path:str, data_str:str):
        # 暗号化
        data = self.fernet.encrypt(data_str.encode())
        # 書き込み
        with open(file_path,"wb") as file:
            file.write(data)
    
    def read(self, file_path:str):
        # 読み込み
        with open(file_path,"rb") as file:
            data = file.read()
        # 復号して返却
        return self.fernet.decrypt(data).decode('shift-jis')

    def csv_write(self, file_path:str, data_list:list):
        # 辞書のリストを文字列に変換
        temp_file = TemporaryFile("w+")
        writer = csv.DictWriter(temp_file, data_list[0].keys())
        writer.writeheader()
        writer.writerows(data_list)
        temp_file.seek(0)
        # 暗号化
        encrypted_data = self.fernet.encrypt(temp_file.read().encode())
        # 書き込み
        with open(file_path,"wb") as file:
            file.write(encrypted_data)

    def csv_read(self, file_path:str):
        # 読み込み
        with open(file_path,"rb") as file:
            data = file.read()
        # 復号
        decrypted_data = self.fernet.decrypt(data).decode('shift-jis')
        # 文字列を辞書のリストに変換して返却
        temp_file = TemporaryFile("w+")
        temp_file.write(decrypted_data)
        temp_file.seek(0)
        reader = csv.DictReader(temp_file)
        return [row for row in reader]

テスト

io = Encryption()

data = [
    {"name":"hoge","age":20},
    {"name":"hoge","age":30},
    {"name":"hoge","age":40},
    {"name":"hoge","age":50},
]

io.csv_write("test.csv", data)
with open("test.csv", "r") as f:
    print("暗号化した状態")
    print(f.read()) # 暗号化した状態
print()
print("復号した状態")
print(io.csv_read("test.csv")) # 復号した状態

Discussion