256비트 (= 32바이트)의 키 값을 가짐.

 

AES는 키 값의 길이와 무관하게 128비트(= 16바이트)의 블록 단위로 암호화를 수행함.

** 코드상으로 보면 subString(0,16)을 한다!

 

만약 128비트보다 작은 블록이 발생하면 패딩 작업을 통해 부족한 부분을 특정값으로 채움.

** 패딩 작업엔 (PKCS5, PKCS7 방식이 있음)

** "AES/CBC/PKCS5Padding" 식으로 작성

 

코드

public class AES256 {
    public static String alg = "AES/CBC/PKCS5Padding";
    private final String key = "hyeryunsKeyMyKeyMyEncryptedKey==";
    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(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 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");
    }
}

'웹개발 지식' 카테고리의 다른 글

문자 바이트  (0) 2023.03.22
백 / 프론트(vue) 연결  (0) 2023.02.03
JOIN 및 쿼리 연산자  (0) 2023.01.30
포스트맨  (0) 2023.01.02
No Mybatis mapper was found in '' package  (0) 2023.01.02

+ Recent posts