解密时出现IllegalBLockSizeException

时间:2012-04-25 19:21:17

标签: java encryption block-cipher

我写了一个加密和解密函数。加密工作正常,但我总是在解密中得到IllegalBlockSizeException。

public static String aes_encrypt (String text, String key) 
{
    SecretKey skey = new SecretKeySpec(key.getBytes(), "AES"); 
    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding", "SunJCE");
    cipher.init(Cipher.ENCRYPT_MODE, skey);

    return new String((cipher.doFinal(text.getBytes())));

}

这里有解密功能:

public static String aes_decrypt (String text, String key) 
{

    SecretKey skey = new SecretKeySpec(key.getBytes(), "AES"); 
    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding", "SunJCE");
    cipher.init(Cipher.DECRYPT_MODE, skey);

    return new String((cipher.doFinal(text.getBytes())));
}

以下是测试此功能的简单主要方法:

public static void main (String args[])
{
    String text = "Hello, world!";
    String key = "nv93h50sk1zh508v";
    String en, de;

    System.out.println("Text: " + text);
    System.out.println("Encrypted: " + (en = aes_encrypt(text, key)) 
            + " length = " + en.length());
    System.out.println("Decrypted: " + (de = aes_decrypt(en, key)));
}

有没有人知道如何"垫"正确加密的字符串,以便我可以解密它? (我尝试用0填充字符串,直到长度为16的倍数,但得到类似string not properly padded的内容。)

由于

1 个答案:

答案 0 :(得分:2)

我认为问题在于您使用String构造函数。这是使用文本编码机制转换为字符串,这可能不会保留字节数组中的每个值 - 系统默认编码中不支持的值可能会被丢弃,使编码数据比应该更短。如果需要字符串表示,请转换为十六进制或base 64编码。并在解密方法开始时反转您在此处使用的任何编码。

这不是填充问题 - 加密调用会填充这个问题,因为你将字节数组编码为一个字符串,所以缺少字节数。

您会在this SO question的答案中找到一些基本的64条指令。