Pythonでファイルを暗号化および復号化する方法は何ですか?
Python内でファイルの暗号化と復号化を行うには、cryptographyやPyCryptoなどの暗号化モジュールを使用することができます。以下にPyCryptoモジュールを使用してファイルの暗号化と復号化を行うサンプルコードを示します:
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
def encrypt_file(input_file, output_file, key):
cipher = AES.new(key, AES.MODE_EAX)
with open(input_file, 'rb') as f_in:
data = f_in.read()
nonce = cipher.nonce
ciphertext, tag = cipher.encrypt_and_digest(data)
with open(output_file, 'wb') as f_out:
f_out.write(nonce)
f_out.write(tag)
f_out.write(ciphertext)
def decrypt_file(input_file, output_file, key):
with open(input_file, 'rb') as f_in:
nonce = f_in.read(16)
tag = f_in.read(16)
ciphertext = f_in.read()
cipher = AES.new(key, AES.MODE_EAX, nonce=nonce)
data = cipher.decrypt_and_verify(ciphertext, tag)
with open(output_file, 'wb') as f_out:
f_out.write(data)
# Generate a random key
key = get_random_bytes(16)
# Encrypt a file
encrypt_file('input.txt', 'encrypted.txt', key)
# Decrypt the encrypted file
decrypt_file('encrypted.txt', 'output.txt', key)
上記の例では、最初にencrypt_file()関数を使用して入力ファイルを暗号化し、その後decrypt_file()関数を使用して暗号化されたファイルを復号化します。暗号化および復号化のプロセスでは、AES暗号アルゴリズムとランダムに生成された16バイトのキーを使用しています。
ファイルの暗号化と復号化を行う際には、必ず鍵をしっかり保管しておくように注意してください。ファイルを正しく復号するために重要です。