java中的加密消息 [英] Encryption message in java

查看:213
本文介绍了java中的加密消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:数据不是块大小对齐

javax.crypto.IllegalBlockSizeException: data not block size aligned

我正在使用Blowfish / ECB / NoPadding,消息是一个xml。

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 = 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; 
         }

} 

有人可以帮助我吗?

谢谢

推荐答案

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

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.

指定填充方案。更改为 Blowfish / CBC / PKCS5Padding 它应该可以正常工作。

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

用空字节手动填充它:

创建一个大小为8的倍数的新数组,然后将旧数组复制到其中。

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;
    }
}

这篇关于java中的加密消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆