암호화(AES)

2018. 10. 2. 13:50Android

반응형

ㅇ AES암호화 : 암/복호화에 사용되는 키가 같음(비밀키) / 대칭키 암호화

public class AES256Chiper {

public static byte[] ivBytes = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };

//AES256 암호화
public static String encode(String data, byte[] secretKey) throws java.io.UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {

byte[] textBytes = data.getBytes("UTF-8");

AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
SecretKeySpec newKey = new SecretKeySpec(secretKey, "AES");

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, newKey, ivSpec);

return Base64.encodeToString(cipher.doFinal(textBytes), Base64.DEFAULT);
}

//AES256 복호화
public static String decode(String data, byte[] secretKey) throws java.io.UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {

byte[] textBytes = Base64.decode(data, Base64.DEFAULT);

AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
SecretKeySpec newKey = new SecretKeySpec(secretKey, "AES");

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, newKey, ivSpec);

return new String(cipher.doFinal(textBytes), "UTF-8");
}

// secretkey generate
public static byte[] generate() throws NoSuchAlgorithmException, UnsupportedEncodingException {
KeyGenerator generator = KeyGenerator.getInstance("AES");
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
generator.init(256, secureRandom);

return generator.generateKey().getEncoded();
}

}

 

java.security.InvalidKeyException: Unsupported key size: 오류 발생시

/**
* JAVA의 기본 정책으로는 AES128 암호화 방식까지만 사용이 가능하므로
* AES256 방식으로 암호화를 하게 되면 아래와 같은 Exceptioin이 발생.


* java.security.InvalidKeyException: Unsupported key size: 26 bytes
* => 찾아보니 AES는 128, 192, 256 비트 키 길이를 허용하는데, AES256이니까 결국 키가 32바이트여야 한다.
* => unlimited length 할 수 있는 jar import해야 함.


* build.gradle에
* implementation files('libs/local_policy.jar')
* implementation files('libs/US_export_policy.jar')
* 추가해야 함.
*/

 

 

 

 

 

 

 

https://smartstore.naver.com/byrollin?

 

바이롤린 : 네이버쇼핑 스마트스토어

내 삶이 즐거워지는 순간, 바이롤린과 함께 ♡

smartstore.naver.com

 

반응형

'Android' 카테고리의 다른 글

MD5, SHA1, SHA256  (0) 2018.10.03
BCrypt 암호화  (0) 2018.10.03
안드로이드 생명주기  (0) 2018.08.17
안드로이드 누가 이상 버전 다중창 막기  (0) 2018.08.17
onSaveInstanceState()  (0) 2018.08.17