반응형
AES 암복호화
- key값의 길이에 따라 AES128, AES192, AES256 으로 구분됨
- AES128 : 키값 16bytes
- AES192 : 키값 24bytes
- AES256 : 키값 32bytes
예제 코드(AES256)
import android.util.Base64;
import java.security.spec.AlgorithmParameterSpec;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class AES256Util {
//키값 32바이트: AES256(24: AES192, 16: AES128)
public static String secretKey = "01234567890123450123456789012345";
public static byte[] ivBytes = "0123456789012345".getBytes();
//AES256 암호화
public static String aesEncode(String str) {
try {
byte[] textBytes = str.getBytes("UTF-8");
AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
SecretKeySpec newKey = new SecretKeySpec(secretKey.getBytes("UTF-8"), "AES");
Cipher cipher = null;
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, newKey, ivSpec);
return Base64.encodeToString(cipher.doFinal(textBytes), Base64.DEFAULT);
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
//AES256 복호화
public static String aesDecode(String str) {
try {
byte[] textBytes = Base64.decode(str, Base64.DEFAULT);
AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
SecretKeySpec newKey = new SecretKeySpec(secretKey.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, newKey, ivSpec);
return new String(cipher.doFinal(textBytes), "UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
}
반응형
'안드로이드' 카테고리의 다른 글
Android 카메라 플래시 제어하기 (0) | 2021.11.20 |
---|---|
Java 교차점 구하기 (0) | 2021.11.20 |
Android 쿠키 동기화(retrofit2, webview) (0) | 2021.11.18 |
Android keystore(debug, release) SHA-1 확인 방법 (1) | 2021.11.18 |
Android Excel 파일 생성 후 공유 (0) | 2021.11.18 |
최근댓글