[java] Jasypt를 사용한 자바 애플리케이션의 암호화된 파일 전송 방법

암호화된 파일을 안전하게 전송하기 위해 Jasypt 라이브러리를 사용하는 방법을 알아보겠습니다. Jasypt는 자바 애플리케이션에서 간단하게 암호화 및 복호화를 수행할 수 있는 도구입니다.

Jasypt 라이브러리 추가

먼저, Jasypt 라이브러리를 프로젝트에 추가해야 합니다. Maven을 사용하는 경우 pom.xml 파일에 다음 의존성을 추가하세요:

<dependencies>
    <dependency>
        <groupId>org.jasypt</groupId>
        <artifactId>jasypt</artifactId>
        <version>1.9.3</version>
    </dependency>
</dependencies>

Gradle을 사용하는 경우 build.gradle 파일에 다음 의존성을 추가하세요:

dependencies {
    implementation 'org.jasypt:jasypt:1.9.3'
}

파일 암호화하기

다음으로, 파일을 암호화하는 코드를 작성해보겠습니다. 암호화된 파일은 안전한 전송을 위해 사용될 것입니다.

import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;

public class FileEncryptionUtil {

    public static void encryptFile(String filePath, String password) {
        try {
            StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
            encryptor.setPassword(password);

            byte[] fileData = Files.readAllBytes(Paths.get(filePath));
            byte[] encryptedData = encryptor.encrypt(fileData);

            String encryptedFilePath = filePath + ".encrypted";
            Files.write(Paths.get(encryptedFilePath), encryptedData);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

암호화할 파일의 경로와 사용할 암호를 매개변수로 전달하여 encryptFile 메소드를 호출하면, 해당 파일이 암호화된 후 .encrypted 확장자를 가진 새로운 파일로 저장됩니다.

암호화된 파일 전송하기

이제 암호화된 파일을 안전하게 전송하는 방법을 알아보겠습니다. 여기서는 파일을 이메일 첨부파일로 전송하는 예제를 사용하겠습니다.

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.Properties;

public class EmailUtil {

    public static void sendEmail(String to, String from, String subject, String body, String attachmentPath, String attachmentPassword) {
        Properties props = new Properties();
        Session session = Session.getInstance(props);

        try {
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
            message.setSubject(subject);
            
            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(body);
            
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);
            
            if (attachmentPath != null && attachmentPassword != null) {
                BodyPart attachmentBodyPart = new MimeBodyPart();
                DataSource source = new FileDataSource(attachmentPath);
                attachmentBodyPart.setDataHandler(new DataHandler(source));
                attachmentBodyPart.setFileName(attachmentPath);
                multipart.addBodyPart(attachmentBodyPart);
            }

            message.setContent(multipart);
            Transport.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

}

sendEmail 메소드는 수신자, 발신자, 제목, 본문, 첨부파일 경로, 첨부파일 암호를 인자로 받아 이메일을 전송합니다. 인증 및 SMTP 서버 설정은 프로퍼티에 따라 자동으로 이루어집니다.

사용 예시

public class Main {
    public static void main(String[] args) {
        String filePath = "path/to/file.txt";
        String password = "encryption-password";
        
        FileEncryptionUtil.encryptFile(filePath, password);
        
        String to = "recipient@example.com";
        String from = "sender@example.com";
        String subject = "Encrypted File";
        String body = "Please find the encrypted file attachment.";
        String attachmentPath = "path/to/file.txt.encrypted";
        String attachmentPassword = password;
        
        EmailUtil.sendEmail(to, from, subject, body, attachmentPath, attachmentPassword);
    }
}

위의 예제에서는 path/to/file.txt 파일을 encryption-password로 암호화하고, 암호화된 파일을 수신자의 이메일 주소로 전송합니다. 첨부파일로 전송하기 전에 파일 확장자가 .encrypted로 변경되고, 수신자는 첨부파일을 복호화하기 위해 동일한 암호를 사용해야 합니다.

이제 Jasypt를 사용하여 자바 애플리케이션에서 파일을 암호화하고 전송하는 방법을 알게 되었습니다. 보안에 민감한 정보를 안전하게 전송하기 위해 파일 암호화를 사용하는 것은 매우 중요합니다.