Encryption message in java

I am using java bouncycastle to perform encryption.

However, when I encrypt a message, it throws an exception for me.

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

I am using Blowfish / ECB / NoPadding and the message is xml.

public static void main(String args[]){ String message = "<abc>ABCDEFG</abc>"; String key = "key"; byte[] b = encrypt(message.getBytes(), key.getBytes()); } public byte[] encrypt(byte encrypt[], byte en_key[]) { try { SecretKeySpec key = new SecretKeySpec(en_key, "Blowfish"); Cipher cipher = Cipher.getInstance("Blowfish/ECB/NoPadding"); cipher.init(Cipher.ENCRYPT_MODE, en_key); return cipher.doFinal(encrypt); } catch (Exception e) { e.printStackTrace(); return null; } } 

Can anyone help me?

thanks

0
source share
2 answers

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.

Indicate the filling scheme. Go to Blowfish/CBC/PKCS5Padding and it should work.

Filling it manually with zero bytes:
Create a new array with a large size that is a multiple of 8, and then copy the old array into it.

 public static byte[] encrypt(byte encrypt[], byte en_key[]) { if(encrypt.length % 8 != 0){ //not a multiple of 8 //create a new array with a size which is a multiple of 8 byte[] padded = new byte[encrypt.length + 8 - (encrypt.length % 8)]; //copy the old array into it System.arraycopy(encrypt, 0, padded, 0, encrypt.length); encrypt = padded; } try { SecretKeySpec key = new SecretKeySpec(en_key, "Blowfish"); Cipher cipher = Cipher.getInstance("Blowfish/ECB/NoPadding"); cipher.init(Cipher.ENCRYPT_MODE, key); return cipher.doFinal(encrypt); } catch (Exception e) { e.printStackTrace(); return null; } } 
+5
source
 public static void main(String args[]){ String message = "<abc>ABCDEFG</abc>"; String key = "key"; byte[] b = encrypt(message.getBytes(), key.getBytes()); } public byte[] encrypt(byte encrypt[], byte en_key[]) { try { SecretKeySpec key = new SecretKeySpec(en_key, "Blowfish"); Cipher cipher = Cipher.getInstance("Blowfish/ECB/NoPadding"); cipher.init(Cipher.ENCRYPT_MODE, en_key); return cipher.doFinal(encrypt); } catch (Exception e) { e.printStackTrace(); return null; } } 
0
source

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


All Articles