[JAV] AES-256 CBC 암복호화

2018. 7. 24. 09:31 - Song's IT

1. JRE의 256 bit 암호화 제한 해제

   - Project Properties BuildPath의 JRE버전과 동일한 버전으로 검색 후 다운로드

     링크 : http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html



2. AES256Cipher.java(EX. AES256Cipher.AES_Encode(str))

import javax.crypto.BadPaddingException;

import javax.crypto.Cipher;

import javax.crypto.IllegalBlockSizeException;

import javax.crypto.NoSuchPaddingException;

import javax.crypto.SecretKey;

import javax.crypto.spec.IvParameterSpec;

import javax.crypto.spec.SecretKeySpec;

import java.security.InvalidKeyException;

import java.security.NoSuchAlgorithmException;

import java.security.InvalidAlgorithmParameterException;

import android.util.*;

 

public class AES256Cipher {

 

 private static volatile AES256Cipher INSTANCE;

 

 final static String secretKey   = "Q!d$2018072316543418070119376805"; //32bit

 static String IV                = "L$b@180701193768"; //16bit

 

 public static AES256Cipher getInstance(){

     if(INSTANCE==null){

         synchronized(AES256Cipher.class){

             if(INSTANCE==null)

                 INSTANCE=new AES256Cipher();

         }

     }

     return INSTANCE;

 }

 

 private AES256Cipher(){

     IV = secretKey.substring(0,16);

    }

 

 // Encryption

 public static String AES_Encode(String str) throws java.io.UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException{

     byte[] keyData = secretKey.getBytes();

 

 SecretKey secureKey = new SecretKeySpec(keyData, "AES");

 

 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");

 c.init(Cipher.ENCRYPT_MODE, secureKey, new IvParameterSpec(IV.getBytes()));

 

 byte[] encrypted = c.doFinal(str.getBytes("UTF-8"));

 String enStr = new String(Base64.encode(encrypted, 2));

 

 return enStr;

 }

 

 // Decryption

 public static String AES_Decode(String str) throws java.io.UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException{

  byte[] keyData = secretKey.getBytes();

  SecretKey secureKey = new SecretKeySpec(keyData, "AES");

  Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");

  c.init(Cipher.DECRYPT_MODE, secureKey, new IvParameterSpec(IV.getBytes("UTF-8")));

 

  byte[] byteStr = Base64.decode(str.getBytes(), 2);

 

  return new String(c.doFinal(byteStr),"UTF-8");

 }

}

'Development > Eclipse' 카테고리의 다른 글

JDBC] Eclipse - MySQL 연동  (0) 2014.08.12
JDBC] 이클립스 & MySQL 연결 확인  (0) 2014.08.12
Eclipse] 프로젝트파일 Import  (0) 2014.08.12

다른 카테고리의 글 목록

Development/Eclipse 카테고리의 포스트를 톺아봅니다