I'm using the following in an android app and a standalone java app:
private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(clear);
...
I get different encrypted strings on android vs my standalone java app (both using the same code and key). I get the same exception (javax.crypto.BadPaddingException: Blocktype mismatch: 0) as in this question:
RSA Encryption: Difference between Java and Android
And the suggested solution is to specify the padding strategy like:
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
but I'm using "AES", not "RSA", and am not sure how to specify the padding in combination with AES. How would I construct the string passed to Cipher.getInstance() in that case? I gave this a try:
Cipher cipher = Cipher.getInstance("AES/PKCS1Padding");
but get an exception about that being invalid.
Thanks
This class provides the functionality of a cryptographic cipher for encryption and decryption. It forms the core of the Java Cryptographic Extension (JCE) framework. In order to create a Cipher object, the application calls the Cipher's getInstance method, and passes the name of the requested transformation to it.
The Java Cipher class encryption and decryption methods can encrypt or decrypt part of the data stored in a byte array. You simply pass an offset and length to the update() and / or doFinal() method. Here is an example: int offset = 10; int length = 24; byte[] cipherText = cipher.
Cipher is not thread safe.
This is how I did it:
keyGenerator.init(new
KeyGenParameterSpec.Builder(KEY_NAME,
KeyProperties.PURPOSE_ENCRYPT |
KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_CBC)
.setUserAuthenticationRequired(true)
.setEncryptionPaddings(
KeyProperties.ENCRYPTION_PADDING_PKCS7)
.build());
cipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With