[Spring] AES 암복호화 InvalidKeyException: Parameters missing

19·2024년 1월 16일

배경

AES로 암호화하고 복호화하려는데 자꾸 InvalidKeyException: Parameters missing예외가 발생했다
결론은 Iv(Initialize Vector)를 설정하지 않아서였다

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

public static String decrypt(String encryptedData, String key) throws Exception {
    SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(CHARSET), ALGORITHM);
    Cipher cipher = Cipher.getInstance(TRANSFORMATION);
    cipher.init(Cipher.DECRYPT_MODE, secretKey);
    byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
    return new String(decryptedBytes, CHARSET);
}
  • AES 알고리즘을 사용해 암호화할 때는, 반드시 Iv를 설정해야 한다고 한다

내가 한 방법

public static String encrypt(String data, String key) throws Exception {
    SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(CHARSET), ALGORITHM);
    Cipher cipher = Cipher.getInstance(TRANSFORMATION);
    **IvParameterSpec ivParameterSpec = new IvParameterSpec(getIV(key).getBytes());**
    cipher.init(Cipher.ENCRYPT_MODE, secretKey, **ivParameterSpec**);
    byte[] encryptedBytes = cipher.doFinal(data.getBytes(CHARSET));
    return Base64.getEncoder().encodeToString(encryptedBytes);
}

public static String decrypt(String encryptedData, String key) throws Exception {
    SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(CHARSET), ALGORITHM);
    Cipher cipher = Cipher.getInstance(TRANSFORMATION);
    **IvParameterSpec ivParameterSpec = new IvParameterSpec(getIV(key).getBytes());**
    cipher.init(Cipher.ENCRYPT_MODE, secretKey, **ivParameterSpec**);
    byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
    return new String(decryptedBytes, CHARSET);
}
  • Iv를 설정해주니 정상 동작

참고

https://velog.io/@coals_0329/Spring-%EC%95%94%ED%98%B8%ED%99%94%EB%B3%B5%ED%98%B8%ED%99%94-%ED%95%98%EA%B8%B0
https://ts2ree.tistory.com/333

profile
하나씩 차근차근

0개의 댓글