ユーザIDとパスワードを暗号化してINIファイルで管理する(Python)

使い方

・write_idとwrite_passwordを使ってユーザ情報を登録する
・read_idとread_passwordをを使ってユーザ情報を取得する
・my.key: 暗号・複合に使うkey情報。ファイルが無い場合は適当に作成する。
・my.ini:ユーザID・パスワード情報

Pythonのコード

from base64 import b64encode, b64decode
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from Crypto.Random import get_random_bytes
import os
import configparser

# Keyファイルの読み込み。keyファイルが内場合は適当に作る。
def read_key():
    if os.path.exists(file_name):
        with open(file_name, 'r') as f:
            key = f.read()
    else:
        with open(file_name, 'w') as f:
            key = b64encode(get_random_bytes(32)).decode('utf-8')
            f.write(key)
    return key

# 暗号化する
def encrypt(key, data):
    key = b64decode(key)
    data = bytes(data, 'utf-8')
    cipher = AES.new(key, AES.MODE_CBC)
    ct_bytes = cipher.encrypt(pad(data, AES.block_size))
    iv = b64encode(cipher.iv).decode('utf-8')
    ct = b64encode(ct_bytes).decode('utf-8')
    return ct, iv

# 復号化する
def decrypt(key, iv, ct):
    key = b64decode(key)
    iv = b64decode(iv)
    ct = b64decode(ct)
    cipher = AES.new(key, AES.MODE_CBC, iv)
    pt = unpad(cipher.decrypt(ct), AES.block_size)
    return pt.decode('utf-8')

#設定ファイル読み込み
def read_config(config_file, section, key):
    config = configparser.ConfigParser()
    config.read(config_file)
    return config.get(section, key)

#設定ファイル書き込み
def write_config(config_file, section, key, value):
    config = configparser.ConfigParser()
    config.read(config_file)
    if not config.has_section(section):
        config.add_section(section)
    config.set(section, key, value)

    with open(config_file, 'w') as configfile:
        config.write(configfile)

def write_id(env,id):
    ct, iv = encrypt(key, id)
    write_config(config_file, env, 'id_01', ct)
    write_config(config_file, env, 'id_02', iv)

def write_password(env,password):
    ct, iv = encrypt(key, password)
    write_config(config_file, env, 'id_03', ct)
    write_config(config_file, env, 'id_04', iv)

def read_id(env):
    ct = read_config(config_file, env, 'id_01')
    iv = read_config(config_file, env, 'id_02')
    return decrypt(key, iv, ct)

def read_password(env):
    ct = read_config(config_file, env, 'id_03')
    iv = read_config(config_file, env, 'id_04')
    return decrypt(key, iv, ct)

# 実行中のファイルのディレクトリを取得
current_dir = os.path.dirname(os.path.abspath(__file__))
# カレントディレクトリを変更
os.chdir(current_dir)

#keyファイル名
file_name="my.key"
# 設定ファイル名
config_file = 'my.ini'
key = read_key()

write_id("prod","prod_user")
write_password("prod","prod_password")

# 結果確認のため、復号したものをprint
print(read_id('prod'))
print(read_password('prod'))

コメント