AES(Advanced Encryption Standard; 고급 암호화 표준)는 암호화 및 복호화를 위한 대칭키 알고리즘이다. 여기서 대칭키란 암호화와 복호화에 동일한 키를 사용하는 방식이다.
AES에는 AES-128, AES-192, AES-256이 있는데 뒤의 숫자는 키의 길이(bit)를 의미한다. 예를들어 키의 길이가 16자리(16byte = 128bit)일 경우 AES-128이 된다.
Java에서 제공하는 SecretKeySpec 클래스와 Cipher 클래스, 그리고 암호의 인코딩 및 디코딩을 위한 Base64를 사용해 AES 알고리즘으로 암호화/복호화를 할 수 있다.
package com.web.ddentist.security;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class AesEncryptionUtil {
// 암호화 알고리즘
private static final String ALGORITHM = "AES";
// 암호화에 사용할 키
private static final byte[] KEY = "aesEncryptTest00".getBytes();
// 암호화
public static String encrypt(String value) {
try {
// SecretKeySpec 인스턴스 생성
SecretKeySpec keySpec = new SecretKeySpec(KEY, ALGORITHM);
// Cipher 인스턴스 생성
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
byte[] encrypted = cipher.doFinal(value.getBytes());
// 암호화 후 인코딩하여 문자열로 반환
return Base64.getEncoder().encodeToString(encrypted);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
// 복호화
public static String decrypt(String encryptedValue) {
try {
SecretKeySpec keySpec = new SecretKeySpec(KEY, ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, keySpec);
// 인코딩된 내용을 디코딩
byte[] decoded = Base64.getDecoder().decode(encryptedValue);
byte[] decrypted = cipher.doFinal(decoded);
// 복호화 후 바이트를 문자열로 변환하여 반환
return new String(decrypted);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
'웹 개발 > 웹 개발' 카테고리의 다른 글
| 파일 삭제 (java.nio.file.Files) (0) | 2023.03.27 |
|---|---|
| 혼합 데이터 타입의 JSON 데이터 받기 (0) | 2023.03.07 |
| sweetalert 2 사용하기 (0) | 2023.02.09 |
| IText 7 - 스탬프 모드 (0) | 2023.02.07 |
| Naver NCloud Platform - SMS 서비스 (0) | 2023.02.06 |