[Java] AES256 암/복호화
by 개발자 우디정의
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(); System.out.println(aes256.encrypt("암호화할 문자"));
복호화
AES256 aes256 = new AES256(); System.out.println(aes256.decrypt("복호화할 문자"));
블로그의 정보
우디의 개발스터디
개발자 우디