[java] Apache Commons VFS를 사용한 암호화와 복호화

Apache Commons VFS는 가상 파일 시스템을 사용하여 암호화와 복호화를 지원하는 강력한 도구입니다. 이 글에서는 Apache Commons VFS를 사용하여 파일을 암호화하고 복호화하는 방법에 대해 알아보겠습니다.

준비 사항

  1. Apache Commons VFS 라이브러리를 다운로드하고 프로젝트에 추가합니다.
  2. 암호화에 사용할 암호화 알고리즘과 키를 준비합니다. 이 예제에서는 AES 알고리즘과 128-bit 길이의 키를 사용합니다.

파일 암호화

아래 코드는 Apache Commons VFS를 사용하여 파일을 암호화하는 예제입니다.

import org.apache.commons.vfs2.*;
import org.apache.commons.vfs2.impl.StandardFileSystemManager;
import org.apache.commons.vfs2.provider.FileProvider;
import org.apache.commons.vfs2.provider.local.DefaultLocalFileProvider;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Key;

public class FileEncryptionExample {
    private static final String KEY_ALGORITHM = "AES";
    private static final String TRANSFORMATION = "AES";

    public static void main(String[] args) throws Exception {
        String inputFilePath = "path/to/input/file";
        String outputFilePath = "path/to/output/file";
        String key = "secretkey";

        File input = new File(inputFilePath);
        File output = new File(outputFilePath);

        StandardFileSystemManager manager = new StandardFileSystemManager();
        manager.addProvider("file", new DefaultLocalFileProvider());

        try {
            manager.init();

            FileSystemOptions fsOptions = new FileSystemOptions();
            CryptoAttributes.setKey(fsOptions, getKeySpec(key));

            FileObject inputFile = manager.resolveFile(input.toURI().toString(), fsOptions);
            FileObject outputFile = manager.resolveFile(output.toURI().toString(), fsOptions);

            try (InputStream inputStream = inputFile.getContent().getInputStream();
                 OutputStream outputStream = outputFile.getContent().getOutputStream()) {
                byte[] buffer = new byte[1024];
                int bytesRead;

                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
            }

            System.out.println("File encrypted successfully!");
        } finally {
            manager.close();
        }
    }

    private static Key getKeySpec(String key) {
        byte[] keyBytes = key.getBytes();
        return new SecretKeySpec(keyBytes, KEY_ALGORITHM);
    }
}

위 예제에서는 입력 파일과 출력 파일의 경로, 암호화에 사용할 키를 설정한 뒤 StandardFileSystemManager를 초기화하고 파일 객체를 생성합니다. FileSystemOptions를 사용하여 암호화 키를 설정한 다음, 입력 파일의 내용을 읽어서 출력 파일에 쓰는 방식으로 암호화를 수행합니다.

파일 복호화

아래 코드는 Apache Commons VFS를 사용하여 암호화된 파일을 복호화하는 예제입니다.

import org.apache.commons.vfs2.*;
import org.apache.commons.vfs2.provider.local.DefaultLocalFileProvider;

import javax.crypto.Cipher;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Key;

public class FileDecryptionExample {
    private static final String KEY_ALGORITHM = "AES";
    private static final String TRANSFORMATION = "AES";

    public static void main(String[] args) throws Exception {
        String inputFilePath = "path/to/encrypted/file";
        String outputFilePath = "path/to/decrypted/file";
        String key = "secretkey";

        File input = new File(inputFilePath);
        File output = new File(outputFilePath);

        StandardFileSystemManager manager = new StandardFileSystemManager();
        manager.addProvider("file", new DefaultLocalFileProvider());

        try {
            manager.init();

            FileSystemOptions fsOptions = new FileSystemOptions();
            CryptoAttributes.setKey(fsOptions, getKeySpec(key));

            FileObject inputFile = manager.resolveFile(input.toURI().toString(), fsOptions);
            FileObject outputFile = manager.resolveFile(output.toURI().toString(), fsOptions);

            try (InputStream inputStream = inputFile.getContent().getInputStream();
                 OutputStream outputStream = outputFile.getContent().getOutputStream()) {
                Cipher cipher = Cipher.getInstance(TRANSFORMATION);
                cipher.init(Cipher.DECRYPT_MODE, getKeySpec(key));

                byte[] buffer = new byte[1024];
                int bytesRead;

                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    byte[] outputBytes = cipher.update(buffer, 0, bytesRead);
                    outputStream.write(outputBytes);
                }

                byte[] outputBytes = cipher.doFinal();
                outputStream.write(outputBytes);
            }

            System.out.println("File decrypted successfully!");
        } finally {
            manager.close();
        }
    }

    private static Key getKeySpec(String key) {
        byte[] keyBytes = key.getBytes();
        return new SecretKeySpec(keyBytes, KEY_ALGORITHM);
    }
}

위 예제에서는 입력 파일과 출력 파일의 경로, 복호화에 사용할 키를 설정한 뒤 StandardFileSystemManager를 초기화하고 파일 객체를 생성합니다. FileSystemOptions를 사용하여 암호화 키를 설정한 다음, 입력 파일의 내용을 읽어서 복호화를 수행한 후 출력 파일에 씁니다.

결론

Apache Commons VFS를 사용하여 파일을 암호화 및 복호화하는 방법에 대해 알아보았습니다. 이를 통해 파일 보안에 대한 강력한 기능을 쉽게 구현할 수 있습니다. Apache Commons VFS의 다양한 기능을 활용해 원하는 파일 암호화 및 복호화 시나리오를 만들어보세요.

참고 자료