[java] Jasypt를 활용한 자바 애플리케이션에서의 파일 시스템 보호 방법
파일 시스템 보호는 애플리케이션의 중요한 측면 중 하나입니다. 암호화를 통해 파일 시스템을 보호할 수 있으며, 이를 위해 Jasypt 라이브러리를 활용할 수 있습니다.
Jasypt는 Java 애플리케이션에서 데이터 암호화를 위한 간편한 방법을 제공하는 라이브러리입니다. 이 라이브러리를 사용하여 파일 시스템에 저장되는 파일을 암호화하고, 필요할 때에만 복호화하여 사용할 수 있습니다.
다음은 Jasypt를 활용하여 파일 시스템을 보호하는 방법의 예시입니다.
1. Jasypt 라이브러리 추가
먼저, 프로젝트의 의존성에 Jasypt 라이브러리를 추가해야 합니다. Maven을 사용하는 경우, pom.xml
파일에 다음 의존성을 추가하세요.
<dependency>
<groupId>org.jasypt</groupId>
<artifactId>jasypt</artifactId>
<version>1.9.3</version>
</dependency>
Gradle을 사용하는 경우, build.gradle
파일에 다음 의존성을 추가하세요.
implementation 'org.jasypt:jasypt:1.9.3'
2. 암호화 및 복호화 로직 작성
암호화 및 복호화는 Jasypt의 BasicTextEncryptor
클래스를 사용하여 처리할 수 있습니다.
import org.jasypt.util.text.BasicTextEncryptor;
import java.io.*;
...
public class FileEncryptionUtil {
public static void encryptFile(String inputFile, String outputFile, String password) throws Exception {
BasicTextEncryptor encryptor = new BasicTextEncryptor();
encryptor.setPassword(password);
try (FileInputStream inputStream = new FileInputStream(inputFile);
FileOutputStream outputStream = new FileOutputStream(outputFile)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
String encryptedData = encryptor.encrypt(new String(buffer, 0, bytesRead));
outputStream.write(encryptedData.getBytes());
}
}
}
public static void decryptFile(String inputFile, String outputFile, String password) throws Exception {
BasicTextEncryptor encryptor = new BasicTextEncryptor();
encryptor.setPassword(password);
try (FileInputStream inputStream = new FileInputStream(inputFile);
FileOutputStream outputStream = new FileOutputStream(outputFile)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
String encryptedData = new String(buffer, 0, bytesRead);
String decryptedData = encryptor.decrypt(encryptedData);
outputStream.write(decryptedData.getBytes());
}
}
}
}
3. 파일 암호화 및 복호화 사용 예시
public class Main {
public static void main(String[] args) throws Exception {
String inputFile = "input.txt";
String encryptedFile = "encrypted.txt";
String decryptedFile = "decrypted.txt";
String password = "password123";
// 파일 암호화
FileEncryptionUtil.encryptFile(inputFile, encryptedFile, password);
// 파일 복호화
FileEncryptionUtil.decryptFile(encryptedFile, decryptedFile, password);
}
}
위 예시에서는 input.txt
파일을 password123
을 사용하여 암호화한 후, encrypted.txt
파일로 저장합니다. 그리고 이를 다시 password123
을 사용하여 복호화하여 decrypted.txt
파일로 저장합니다.
Jasypt를 활용한 파일 시스템의 보호는 중요한 개인 데이터를 저장하는 애플리케이션에서 유용합니다. 암호화는 외부에서 파일에 접근하는 것을 방지하고, 필요한 경우에만 데이터를 복호화하여 사용할 수 있도록 합니다.