How to solve javax.crypto.IllegalBlockSizeException: data is not aligned by block size

I am doing a job about using blowfish to encrypt and decrypt in java.

I added a provider and got an instance of "Blowfish / ECB / NoPadding", but I still get this error when I do the encryption.

Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); 

eg:.

 public static byte[] encrypt(byte to_encrypt[], byte strkey[]) { try { SecretKeySpec key = new SecretKeySpec(strkey, "Blowfish"); Cipher cipher = Cipher.getInstance("Blowfish/ECB/NoPadding"); cipher.init(Cipher.ENCRYPT_MODE, key); return cipher.doFinal(to_encrypt); // <=========== error } catch (Exception e) { e.printStackTrace(); return null; } } 

leads to

 javax.crypto.IllegalBlockSizeException: data not block size aligned at org.bouncycastle2.jce.provider.JCEBlockCipher.engineDoFinal(JCEBlockCipher.java:686) at javax.crypto.Cipher.doFinal(Cipher.java:1171) 

Thanks.

+5
source share
2 answers

You explicitly asked for a provider that does not NoPadding (note the NoPadding in the instance name). Therefore, your entry will not be supplemented.

In addition, it is a block cipher, so the input must be a multiple of the length of the block. If the crypto provider does not register, you need to make sure that your input is a multiple of the block size, otherwise encryption / decryption will not be possible, and you will get this error.

Thus, you have two options to solve this problem:

  • Insert the tab yourself in several block sizes.
  • Select the provider that performs the addition (for example, PKCS5Padding ) if you do not want to do this manually. Given the nature of your question, this is probably the best option.
+9
source

You are using NoPadding , and the size of your input should not match the size of the encryption block, so an IllegalBlockSizeException is IllegalBlockSizeException . If you use NoPadding, you need to make sure your input is a multiple of 8 bytes.

Try to specify a fill pattern. Go to Blowfish/CBC/PKCS5Padding and it should work.

+3
source

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


All Articles