Error AES-256 and PKCS7Padding in Java

I have several libraries, C #, PHP and Android, where they all encrypt / decrypt the string in the same way, so they are all compatible with each other, i.e. c # writes and encrypts the data to the database, and PHP can successfully decrypt and return the original string.

Now I need to do the same with a standard Java application, so I took the code from my Android library and I need libraries, but I get an exception. As far as I know, the code was not specific to Android, so this should not be a problem.

Below is my encryption function

public static String encrypt(String plainPasword) { String password = ""; try { SecretKeySpec key = new SecretKeySpec("hcxilkqbbhczfeultgbskdmaunivmfuo".getBytes("US-ASCII"), "AES"); IvParameterSpec iv = new IvParameterSpec("ryojvlzmdalyglrj".getBytes("US-ASCII")); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding"); cipher.init(Cipher.ENCRYPT_MODE, key, iv); byte[] encoded = cipher.doFinal(plainPasword.getBytes()); password = new String(Base64.encodeBase64(encoded)); } catch (Exception ex) { System.err.println("Encryption Exception: " + ex.toString()); } return password; } 

When I call Encryption.encrypt("myString") , I get the following exception:

 Encryption Exception: java.security.NoSuchAlgorithmException: Cannot find any provider supporting AES/CBC/PKCS7Padding 

As I said, this code works great on Android and it doesn't matter where it gets from.

Update

I found that I need PKCS5Padding instead of 7 thanks to the comment link. Now I get the following exception:

 Encryption Exception: java.security.InvalidKeyException: Illegal key size 
+6
source share
2 answers

First, in Java, the standard indentation is PKCS5Padding, not PKCS7Padding. Java actually does PKCS # 7 padding, but PKCS5Padding is the name in the JCA specification.

Then you try to use AES-256, so you will need to install the policy files Unlimited jurisdiction .

Hope this is just an example and you are not using the same IV for every post, right?

+18
source

@Boardy If you are still facing the problem, then I think you should use MessageDigest, which is compatible for both C # and Java. I came across a similar problem for encrypting and decrypting AES 256. An example code will be as follows.

 public static String encryptWithAES256(String strToEncrypt) throws Exception { MessageDigest digest = MessageDigest.getInstance("SHA-256"); byte[] encodedhash = digest.digest(KEY.getBytes(StandardCharsets.UTF_8)); IvParameterSpec ivspec = new IvParameterSpec(Arrays.copyOf(KEY.getBytes(),16)); SecretKeySpec secretKey = new SecretKeySpec(encodedhash, AES_ENCRYPTION_ALGORITHM); Cipher cipher = Cipher.getInstance(CIPHER_TRANSFORMATION); cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivspec); return new String(Base64.encodeBase64(cipher.doFinal(strToEncrypt.getBytes(CHARACTER_ENCODING)))); } 
-1
source

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


All Articles