본문 바로가기

Android

AES256 encode,decode 를 해보자

public class EncryptionHelper {

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

private static String key = "KEY";



public static String AES_Encode(String str) {


byte[] textBytes = new byte[0];

Cipher cipher = null;

String result = null;

try {

textBytes = str.getBytes("UTF-8");

AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);

SecretKeySpec newKey = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

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

cipher.init(Cipher.ENCRYPT_MODE, newKey, ivSpec);

result = Base64.encodeToString(cipher.doFinal(textBytes), 0);

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

} catch (InvalidKeyException e) {

e.printStackTrace();

} catch (NoSuchAlgorithmException e) {

e.printStackTrace();

} catch (NoSuchPaddingException e) {

e.printStackTrace();

} catch (InvalidAlgorithmParameterException e) {

e.printStackTrace();

} catch (BadPaddingException e) {

e.printStackTrace();

} catch (IllegalBlockSizeException e) {

e.printStackTrace();

}


return result.trim();


}

public static String AES_Decode(String str) {

byte[] textBytes =Base64.decode(str, 0);

String result = null;

try{

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

AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);

SecretKeySpec newKey = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

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

cipher.init(Cipher.DECRYPT_MODE, newKey, ivSpec);

result =  new String(cipher.doFinal(textBytes), "UTF-8");

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

} catch (InvalidKeyException e) {

e.printStackTrace();

} catch (NoSuchAlgorithmException e) {

e.printStackTrace();

} catch (NoSuchPaddingException e) {

e.printStackTrace();

} catch (InvalidAlgorithmParameterException e) {

e.printStackTrace();

} catch (BadPaddingException e) {

e.printStackTrace();

} catch (IllegalBlockSizeException e) {

e.printStackTrace();

}

return  result;

}

}