๐AES256Cipher.java
package com.hyesun.aesencdec;
import com.google.firebase.crashlytics.buildtools.reloc.org.apache.commons.codec.binary.Base64;
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;
public class AES256Cipher {
private static volatile AES256Cipher INSTANCE;
final static String secretKey = "hyesunhyesun99hyesunhyesun99hyes"; //32bit
static String IV = ""; //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);
}
//์ํธํ
public static String AES_Encrypt(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.encodeBase64(encrypted));
return enStr;
}
//๋ณตํธํ
public static String AES_Decrypt(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.decodeBase64(str.getBytes());
return new String(c.doFinal(byteStr), "UTF-8");
}
}
๐์ฌ์ฉ์์
์ํธํ
String strTest ="hyesun";
AES256Cipher a256 = AES256Cipher.getInstance();
String strResult = a256.AES_Encrypt(strTest);
๋ณตํธํ
AES256Cipher a256 = AES256Cipher.getInstance();
String strResult = a256.AES_Decrypt(์ํธํ๋๋ฌธ์์ด);