소스
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");
}
}
TEST
public class MainAES {
public static void main(String[] args) throws Exception {
String key = "aes256-test-key!!"; // key는 16자 이상
AES256Util aes256 = new AES256Util(key);
String text = "암호화되지 않은 문자입니다.";
String encText = aes256.aesEncode(text);
String decText = aes256.aesDecode(encText);
System.out.println("암호화할 문자 : " + text);
System.out.println("암호화된 문자 : " + encText);
System.out.println("복호화된 문자 : " + decText);
}
출처 :
http://woniperstory.tistory.com/216
'Study > Android' 카테고리의 다른 글
[Android ] Listview 위아래 스크롤 감지, ListView Focus (0) | 2019.06.12 |
---|---|
[Android] 단말기 고유값 구하는 방법들 (0) | 2019.06.12 |
[Android] Proguard(프로가드) 추가 (0) | 2019.06.12 |
[Android] 맥에서 안드로이드 apk 디컴파일 하기 (0) | 2019.06.12 |
[Android] 채널 새로고침, 핀치 투 줌(Pinch-To-Zoom) 라이브러리, Custom ToogleButton (0) | 2019.06.12 |