프로젝트를 진행하면서 채팅 메세지를 저장해야하는데 개인정보 문제때문에 이때 이를 암호화해 저장을 해야한다. 그래서 암호화를 위해 aes 알고리즘을 이용했다.
public class Aes128 {
private static final String aes128SecretKey = "비밀키";
public static byte[] aes128ivBytes = aes128SecretKey.getBytes();
public static byte[] aes128ivBytesUtf8 = aes128SecretKey.getBytes(StandardCharsets.UTF_8);
public static String getAES128encode(String encodeData) {
String result = "";
try {
//aes128 비밀키 사용해 인코딩 수행
byte[] textBytes = encodeData.getBytes("UTF-8");
AlgorithmParameterSpec ivSpec = new IvParameterSpec(aes128ivBytes);
SecretKeySpec newKey = new SecretKeySpec(aes128ivBytesUtf8, "AES");
Cipher cipher = null;
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, newKey, ivSpec);
return Base64Utils.encodeToString(cipher.doFinal(textBytes));
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static String getAES128decode(String decodeData) {
String result = "";
try {
//인풋으로 들어온 base64 문자열 데이터를 디코딩 수행 실시
byte[] textBytes = Base64Utils.decode(decodeData.getBytes());
AlgorithmParameterSpec ivSpec = new IvParameterSpec(aes128ivBytes);
SecretKeySpec newKey = new SecretKeySpec(aes128ivBytesUtf8, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, newKey, ivSpec);
// 메세지 데이터 반환 실시
return new String(cipher.doFinal(textBytes), "UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
return result;
}