Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
742 views
in Technique[技术] by (71.8m points)

java - How to solve javax.crypto.IllegalBlockSizeException: data not block size aligned

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...