[java] Apache Commons IO를 이용한 파일 암호화와 복호화 처리하기

파일을 암호화하고 복호화하는 작업은 보안적인 요구사항을 충족시키기 위해 중요한 부분입니다. 이를 위해 Apache Commons IO 라이브러리를 사용하여 파일 암호화와 복호화를 처리할 수 있습니다.

Apache Commons IO란?

Apache Commons IO는 Apache Software Foundation이 개발한 자바 라이브러리로, 파일 및 디렉토리 작업을 보다 쉽게 처리할 수 있도록 도와줍니다.

파일 암호화하기

먼저, 파일을 암호화하는 방법을 살펴보겠습니다. 암호화 작업에는 Java의 Cipher 클래스를 사용하며, Apache Commons IO의 FileUtils를 사용하여 파일을 읽고 쓸 수 있습니다.

import org.apache.commons.io.FileUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;

public class FileEncryptionUtils {

    private static final String ENCRYPTION_ALGORITHM = "AES";
    private static final String ENCRYPTION_KEY = "myencryptionkey";

    public static void encryptFile(File inputFile, File outputFile) throws Exception {
        byte[] encryptionKeyBytes = ENCRYPTION_KEY.getBytes(StandardCharsets.UTF_8);
        SecretKeySpec secretKey = new SecretKeySpec(encryptionKeyBytes, ENCRYPTION_ALGORITHM);
        Cipher cipher = Cipher.getInstance(ENCRYPTION_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        
        byte[] inputFileBytes = Files.readAllBytes(inputFile.toPath());
        byte[] encryptedBytes = cipher.doFinal(inputFileBytes);

        FileUtils.writeByteArrayToFile(outputFile, encryptedBytes);
    }

}

위의 예제에서는 ENCRYPTION_ALGORITHM 변수에 암호화에 사용할 알고리즘을, ENCRYPTION_KEY 변수에 사용할 키 값을 설정합니다. encryptFile 메서드는 입력 파일과 출력 파일을 받아와 암호화를 수행한 후, 출력 파일에 암호화된 내용을 저장합니다.

파일 복호화하기

이번에는 암호화된 파일을 복호화하는 방법을 알아보겠습니다. 암호화와 마찬가지로 Cipher 클래스와 FileUtils를 사용하며, 복호화 메서드를 추가하면 됩니다.

public class FileEncryptionUtils {

    // ...

    public static void decryptFile(File inputFile, File outputFile) throws Exception {
        byte[] encryptionKeyBytes = ENCRYPTION_KEY.getBytes(StandardCharsets.UTF_8);
        SecretKeySpec secretKey = new SecretKeySpec(encryptionKeyBytes, ENCRYPTION_ALGORITHM);
        Cipher cipher = Cipher.getInstance(ENCRYPTION_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);

        byte[] inputFileBytes = Files.readAllBytes(inputFile.toPath());
        byte[] decryptedBytes = cipher.doFinal(inputFileBytes);

        FileUtils.writeByteArrayToFile(outputFile, decryptedBytes);
    }

}

decryptFile 메서드는 마찬가지로 입력 파일과 출력 파일을 받아와 복호화를 수행한 후, 출력 파일에 복호화된 내용을 저장합니다.

사용 예제

이제 파일 암호화와 복호화를 사용하는 예제를 살펴보겠습니다.

import java.io.File;

public class Main {

    public static void main(String[] args) {
        File inputFile = new File("input.txt");
        File encryptedFile = new File("encrypted.txt");
        File decryptedFile = new File("decrypted.txt");
        
        try {
            FileEncryptionUtils.encryptFile(inputFile, encryptedFile);
            FileEncryptionUtils.decryptFile(encryptedFile, decryptedFile);
            System.out.println("암호화와 복호화가 성공적으로 완료되었습니다.");
        } catch (Exception e) {
            System.out.println("오류가 발생하였습니다: " + e.getMessage());
        }
    }

}

위의 예제에서는 input.txt 파일을 암호화한 후 encrypted.txt 파일에 저장하고, 이후에 다시 복호화하여 decrypted.txt 파일에 저장합니다.

결론

Apache Commons IO를 사용하여 파일 암호화와 복호화를 간단하게 처리할 수 있습니다. 이를 통해 안전한 파일 처리 작업을 보다 쉽게 구현할 수 있습니다.

참고 자료