게으른 개발자의 끄적거림

Java 암호화 복호화 간단 코드(feat. AES)

끄적잉 2023. 5. 24. 21:42
반응형

 AES 알고리즘을 사용하여 문자열을 암호화하고 복호화합니다. KEY 변수에는 암호화에 사용할 키를 설정합니다. 암호화된 문자열은 Base64 인코딩하여 반환되며, 복호화할 때는 Base64 디코딩을 수행한 후 복호화를 진행합니다.

 

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class EncryptionExample {
    private static final String ALGORITHM = "AES";
    private static final String KEY = "mysecretkey12345"; // 암호화에 사용할 키 (16, 24, 32 bytes)

    public static String encrypt(String plainText) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(KEY.getBytes(StandardCharsets.UTF_8), ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    public static String decrypt(String encryptedText) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(KEY.getBytes(StandardCharsets.UTF_8), ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] encryptedBytes = Base64.getDecoder().decode(encryptedText);
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }

    public static void main(String[] args) {
        try {
            String plainText = "Hello, World!";
            String encryptedText = encrypt(plainText);
            String decryptedText = decrypt(encryptedText);

            System.out.println("Plain Text: " + plainText);
            System.out.println("Encrypted Text: " + encryptedText);
            System.out.println("Decrypted Text: " + decryptedText);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

반응형

'게으른 개발자의 끄적거림' 카테고리의 다른 글

Java https 소켓통신 방법  (0) 2023.05.30
JavaScript Ajax 초간단 예제  (0) 2023.05.26
Java Xss 대처 방안  (0) 2023.05.23
AES 256 암호화, 복호화 방법  (0) 2023.05.22
JSTL 설명 및 사용 방법  (0) 2023.05.21