8

I am doing an assignment about use blowfish to do encryption & decryption in java.

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

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

e.g.:

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)

Thank you.

1
  • Did use of padding work for you, could you please share the fixed code? Commented Jul 25, 2017 at 10:14

2 Answers 2

14

You've explicitly asked for a provider that doesn't do padding (notice the NoPadding in the instance name). Consequently, your input will not be padded.

Furthermore, this is a block cipher, so the input must be a multiple of the block length. With the crypto provider not doing padding, you need to ensure yourself that your input is a multiple of the block size, else encryption/decryption will not be possible and you'll get this error.

Thus you have two options in order to solve this:

  1. Pad the input yourself to a multiple of the block size.
  2. Choose a provider that does padding (e.g. PKCS5Padding), if you don't want to do it manually. Given the nature of your question, this is likely to be the best option.
Sign up to request clarification or add additional context in comments.

2 Comments

@Shivam657: There is no "the code". This question was about the underlying reasons for the exception, and I've explained what it means in this answer. Assuming you're having the same problem, you need to take note of the information above, and integrate it into your code according to its current structure.
Okay, got it, but could you please explain how do I find the standard block size, I need to find that to pad the input to a multiple of the block size.
4

You are using NoPadding and the size of your input data must not match the block size of the cipher, so an IllegalBlockSizeException is being thrown. If you use NoPadding you need to make sure that your input is a multiple of 8 bytes.

Try specifying a padding scheme. Change to Blowfish/CBC/PKCS5Padding and it should work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.