유틸로 만들어 불러다 사용하면 편할 것 같아 정리해 둔다.
package com.test.board.common.util;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class AES256 {
public static String alg = "AES/CBC/PKCS5Padding";
private final String key = "12345678910111213";
private final String iv = key.substring(0, 16); // 16byte
public String encrypt(String text) throws Exception {
Cipher cipher = Cipher.getInstance(alg);
SecretKeySpec keySpec = new SecretKeySpec(iv.getBytes(), "AES");
IvParameterSpec ivParamSpec = new IvParameterSpec(iv.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivParamSpec);
byte[] encrypted = cipher.doFinal(text.getBytes("UTF-8"));
return Base64.getEncoder().encodeToString(encrypted);
}
public String decrypt(String cipherText) throws Exception {
Cipher cipher = Cipher.getInstance(alg);
SecretKeySpec keySpec = new SecretKeySpec(iv.getBytes(), "AES");
IvParameterSpec ivParamSpec = new IvParameterSpec(iv.getBytes());
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivParamSpec);
byte[] decodedBytes = Base64.getDecoder().decode(cipherText);
byte[] decrypted = cipher.doFinal(decodedBytes);
return new String(decrypted, "UTF-8");
}
}
AES256 aes256 = new AES256();
param.setName(aes256.encrypt(param.getName()));
public String getName() {
AES256 aes256 = new AES256();
try {
return aes256.decrypt(name);
}catch (Exception e){
return name;
}
}
key를 멤버 변수로 선언하고 사용을 안하고 있는데요. 그리고 SecretKeySpec을 생성할 때 왜 iv값을 쓰죠?