Java aes256 암호화 복호화

2017. 10. 31. 20:56·DEV/Spring

1. mvn의 경우 pom.xml에 commons-codec dependency를 추가해준다.

2. https://mvnrepository.com/artifact/commons-codec/commons-codec 원하는 버전을 선택한다.

3. util package를 만들어주고, AES256Util.java를 만든다.

package com.test.api.util;
 
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
 
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
 
import org.apache.commons.codec.binary.Base64;
 
public class AES256Util {
    private String iv;
    private Key keySpec;
    
    public AES256Util(String key) throws UnsupportedEncodingException {
        this.iv = key.substring(0, 16);
        
        byte[] keyBytes = new byte[16];
        byte[] b = key.getBytes("UTF-8");
        int len = b.length;
        if (len > keyBytes.length) {
            len = keyBytes.length;
        }
        System.arraycopy(b, 0, keyBytes, 0, len);
        SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
        
        this.keySpec = keySpec;
    }
 
    // 암호화
    public String aesEncode(String str) throws java.io.UnsupportedEncodingException, 
                                                    NoSuchAlgorithmException, 
                                                    NoSuchPaddingException, 
                                                    InvalidKeyException, 
                                                    InvalidAlgorithmParameterException, 
                                                    IllegalBlockSizeException, 
                                                    BadPaddingException {
        Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
        c.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(iv.getBytes()));
 
        byte[] encrypted = c.doFinal(str.getBytes("UTF-8"));
        String enStr = new String(Base64.encodeBase64(encrypted));
 
        return enStr;
    }
 
    //복호화
    public String aesDecode(String str) throws java.io.UnsupportedEncodingException,
                                                        NoSuchAlgorithmException,
                                                        NoSuchPaddingException, 
                                                        InvalidKeyException, 
                                                        InvalidAlgorithmParameterException,
                                                        IllegalBlockSizeException, 
                                                        BadPaddingException {
        Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
        c.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(iv.getBytes("UTF-8")));
 
        byte[] byteStr = Base64.decodeBase64(str.getBytes());
 
        return new String(c.doFinal(byteStr),"UTF-8");
    }
 
}


#controller


String key = "aes256-test-key!!";    //key는 16자 이상
AES256Util aes256 = new AES256Util(key);
URLCodec codec = new URLCodec();

String enc_key = codec.encode(aes256.aesEncode(암호화할 키)); 
String dec_key = aes256.aesDecode(codec.decode(복호화할 키));
출처: http://aramk.tistory.com/32 [깨순이네]
저작자표시 비영리 변경금지 (새창열림)

'DEV > Spring' 카테고리의 다른 글

파일 업로드 & 다운로드  (0) 2017.11.21
JSTL requestScope 예제  (0) 2017.10.27
JDK 설치, 환경변수 설정  (0) 2017.10.25
이클립스 자동 import  (0) 2017.09.26
이클립스 자동 세미콜론  (0) 2017.09.26
'DEV/Spring' 카테고리의 다른 글
  • 파일 업로드 & 다운로드
  • JSTL requestScope 예제
  • JDK 설치, 환경변수 설정
  • 이클립스 자동 import
modric
modric
  • modric
    dev log
    modric
  • 전체
    오늘
    어제
    • 분류 전체보기 (70)
      • DEV (58)
        • Linux (12)
        • JavaScript (5)
        • PHP (4)
        • MySql (4)
        • HTML (7)
        • CSS (9)
        • Spring (13)
        • flutter (1)
        • 오류 (2)
        • devOps (1)
      • 기타 (5)
      • 트렌드 (1)
  • 블로그 메뉴

    • 홈
    • 태그
    • 미디어로그
    • 위치로그
    • 방명록
    • HTML
    • CSS
    • PHP
    • JavaScript
    • Spring
    • Linux
  • 링크

    • 공부하는 소담아빠
    • 타올이
  • 공지사항

  • 인기 글

  • 태그

    height
    터치
    exist
    php
    Destination
    Android
    linux
    테두리
    centos 7
    mariadb10
    mariadb 10
    ios
    클릭
    메타버스
    js
    넘침
    컴파일
    lastinsertid
    팩토리얼
    제거
    크롬
    update
    파란색
    factorial
    MYSQL
    build
    iframe
    centos7
    100!
    Safari
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.5
modric
Java aes256 암호화 복호화
상단으로

티스토리툴바