Java AES256 암/복호화

Woody·2022년 1월 2일
post-thumbnail

유틸로 만들어 불러다 사용하면 편할 것 같아 정리해 둔다.

클래스 정의

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");
    }
}

사용 예시

  1. 암호화
AES256 aes256 = new AES256();
param.setName(aes256.encrypt(param.getName()));
  1. 복호화
public String getName() {
	AES256 aes256 = new AES256();
	try {
		return aes256.decrypt(name);
	}catch (Exception e){
		return name;
	}
}
profile
If the wind will not serve, take to the oars

1개의 댓글

comment-user-thumbnail
2023년 5월 7일

key를 멤버 변수로 선언하고 사용을 안하고 있는데요. 그리고 SecretKeySpec을 생성할 때 왜 iv값을 쓰죠?

답글 달기