개발/JAVA

AES-256 암복호화 예제

LukeHan1128 2024. 2. 14. 20:00
반응형

 

package com.verywords.fw.core.util;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class AESUtil{
  public static String alg = "AES/CBC/PKCS5Padding";
  private static final String key = "BLOG_LUKEHAN_KR-LukeHan";
  private static final String iv = key.substring(0, 16);

  public static String encrypt(String text) throws Exception{
    Cipher cipher = Cipher.getInstance(alg);
    SecretKeySpec keySpec = new SecretKeySpec(key.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 static String decrypt(String cipherText) throws Exception{
    Cipher cipher = Cipher.getInstance(alg);
    SecretKeySpec keySpec = new SecretKeySpec(key.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");
  }
}

 

 

 

 

참고

 

반응형