Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify Cipher.getInstance() arguments?

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

like image 963
user291701 Avatar asked Jul 01 '12 05:07

user291701


People also ask

What is cipher getInstance?

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.

How do you use cipher in Java?

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.

Is cipher getInstance thread safe?

Cipher is not thread safe.


1 Answers

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);
like image 131
Skrettinga Avatar answered Oct 09 '22 19:10

Skrettinga