[python] M2Crypto를 이용하여 파일을 암호화하는 방법은 어떻게 되나요?

먼저, M2Crypto를 설치합니다. 다음은 파일을 암호화하는 예제 코드입니다.

먼저, M2Crypto를 설치합니다.

pip install M2Crypto

다음은 파일을 암호화하는 예제 코드입니다.

from M2Crypto import EVP
import os

def encrypt_file(input_file, output_file, passphrase):
    key = EVP.Cipher(alg='aes_256_cbc', key=os.urandom(32), iv=os.urandom(16), op=1, key_as_bytes=1, d='md5')
    key.set_passthrough_data(passphrase.encode())
    
    with open(input_file, 'rb') as f_in, open(output_file, 'wb') as f_out:
        while True:
            buf = f_in.read(1024)
            if not buf:
                break
            f_out.write(key.update(buf))
        f_out.write(key.final())

encrypt_file('input.txt', 'encrypted_output.enc', 'mypassword')

위 코드에서 encrypt_file 함수는 입력 파일을 읽고, 대칭키를 생성한 후 파일을 암호화하여 출력 파일에 저장하는 과정을 수행합니다. aes_256_cbc 알고리즘을 사용하여 대칭키를 설정하고 입력된 passphrase를 이용하여 키를 설정하고 있습니다.

이렇게 암호화된 파일은 복호화를 위해 동일한 passphrase를 사용하여 다시 복호화할 수 있습니다.

M2Crypto의 다양한 기능을 활용하여 파일 암호화 및 복호화를 수행할 수 있습니다.