Skip to content

Instantly share code, notes, and snippets.

@nguyenlinhnttu
Created August 29, 2019 06:59
Show Gist options
  • Save nguyenlinhnttu/bc75136902752894d819304b4ab31a48 to your computer and use it in GitHub Desktop.
Save nguyenlinhnttu/bc75136902752894d819304b4ab31a48 to your computer and use it in GitHub Desktop.
AES256Cipher Android
public class AES256Cipher {
public static byte[] ivBytes = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
public static String AES_Encode(String str, String str2) throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
byte[] bytes = str.getBytes("UTF-8");
IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);
SecretKeySpec secretKeySpec = new SecretKeySpec(str2.getBytes("UTF-8"), "AES");
Cipher instance = Cipher.getInstance("AES/CBC/PKCS5Padding");
instance.init(1, secretKeySpec, ivParameterSpec);
return Base64.encodeToString(instance.doFinal(bytes), 0);
}
public static String AES_Decode(String str, String str2) throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
byte[] decode = Base64.decode(str, 0);
IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);
SecretKeySpec secretKeySpec = new SecretKeySpec(str2.getBytes("UTF-8"), "AES");
Cipher instance = Cipher.getInstance("AES/CBC/PKCS5Padding");
instance.init(2, secretKeySpec, ivParameterSpec);
return new String(instance.doFinal(decode), "UTF-8");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment