Specify arguments to Cipher.getInstance ()?

I use the following in an Android app and standalone java application:

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 in android vs my standalone java application (both use the same code and key). I get the same exception (javax.crypto.BadPaddingException: label mismatch: 0), as in this question:

RSA Encryption: The Difference Between Java and Android

And the proposed solution is to indicate a filling strategy, for example:

 Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); 

but I use "AES" and not "RSA", and I don’t know how to specify an addition in combination with AES. How would I build the string passed to Cipher.getInstance (), in this case? I tried:

 Cipher cipher = Cipher.getInstance("AES/PKCS1Padding"); 

but get an exception due to invalid.

thanks

+6
source share
3 answers

Another "short answer", but I believe that AES-GCM is more secure in CBC mode and exists for several years, but if you want to use Android, you need to enable spongycastle

 Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); 
+5
source

Short answer:

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

long answer

+4
source

Here 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); 
0
source

Source: https://habr.com/ru/post/919416/


All Articles