Encryption message in java
i am a project about using java's bouncycastle to do the encryption.
However, when I encrypt the message, it throws an exception for me.
javax.crypto.IllegalBlockSizeException: data not block size aligned
I am using Blowfish/ECB/NoPadding, and the message is an xml.
public static void main(String args[]){
String message = "<abc>ABCDEFG</abc>";
String key = "key";
byte[] b = 开发者_如何学Cencrypt(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;
}
}
Could anyone can help me?
Thank you
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.
Specify a padding scheme. Change to Blowfish/CBC/PKCS5Padding
and it should work.
Padding it manually with null bytes:
Create a new array with a bigger 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;
}
}
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;
}
}
精彩评论