java中的加密消息

Roy*_*Roy 0 java

我是一个关于使用java的bouncycastle进行加密的项目.

但是,当我加密消息时,它会为我抛出异常.

javax.crypto.IllegalBlockSizeException:数据不是块大小对齐

我正在使用Blowfish/ECB/NoPadding,消息是一个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; 
         }

} 
Run Code Online (Sandbox Code Playgroud)

任何人都可以帮助我吗?

谢谢

dog*_*ane 5

您正在使用NoPadding,输入数据的大小必须与密码的块大小不匹配,因此IllegalBlockSizeException正在抛出.如果使用NoPadding,则需要确保输入是8字节的倍数.

指定填充方案.改变Blowfish/CBC/PKCS5Padding,它应该工作.

用空字节手动填充它:
创建一个大小为8的倍数的新数组,然后将旧数组复制到其中.

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;
    }
}
Run Code Online (Sandbox Code Playgroud)