[Cryptography] Java AES 128 암호화 예제

AES 128bit 임으로 string length 16인(16 * 8 = 128bit) key를 넣어 준다.

public String encryptByAES(String plain, String key) {
    try {
        SecretKeySpec spec = new SecretKeySpec(key.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, spec);

        byte[] encTxt = cipher.doFinal(plain.getBytes());

        return Base64.getEncoder().encodeToString(encTxt);
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Cipher exception: " + e.getMessage());
    }
}

// encTxt: base64 encoded.
public String decryptByAES(String b64EncTxt, String key) {
    try {
        SecretKeySpec spec = new SecretKeySpec(key.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, spec);

        byte[] b64Decoded = Base64.getDecoder().decode(b64EncTxt.getBytes());
        byte[] plain = cipher.doFinal(b64Decoded);

        return new String(plain);
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Cipher exception: " + e.getMessage());
    }
}

댓글

이 블로그의 인기 게시물

[Protocol] WIEGAND 통신

Orange for Oracle에서 한글 깨짐 해결책

[UI] GNB·LNB·SNB·FNB 용어 설명