解密中的CipherClass异常

时间:2014-11-19 18:05:49

标签: encryption cryptography aes

CipherClass的解密异常: 加密部分运行顺畅 解密会引发以下异常:

Exception in thread "main" javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher
    at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:913)
    at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:824)
    at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:436)
    at javax.crypto.Cipher.doFinal(Cipher.java:2121)
    at rmihello.EncryptionModule.decryptText(EncryptionModule.java:23)
    at rmihello.Client.main(Client.java:56)

这是我的代码:(我从一个测试类调用,它有一个secretKey和一条消息)

import javax.crypto.Cipher;
import javax.crypto.SecretKey;

public class EncryptionModule {

    /**
     * Encrypts
     */
    public static String encryptText(String plainText, SecretKey key) throws Exception{
        Cipher c = Cipher.getInstance("AES/ECB/PKCS5Padding");
        c.init(Cipher.ENCRYPT_MODE, key);
        byte[] cipherT =  c.doFinal(plainText.getBytes());
        return new String(cipherT,"utf-8");
    }
    /**
     * Decrypts
     */
    public static String decryptText(String cipherText, SecretKey key) throws Exception{
        Cipher c = Cipher.getInstance("AES/ECB/PKCS5Padding");
        c.init(Cipher.DECRYPT_MODE, key);
        byte[] clearT =  c.doFinal(cipherText.getBytes());
        return new String(clearT,"utf-8");
    }
}

1 个答案:

答案 0 :(得分:0)

您不能使用String来存储具有随机值的字节,并且加密应始终返回无法与随机区分的结果。改为使用base 64(或用于人类消费,十六进制)编码。

为了兼容性,我强烈建议您使用明文编码的特定字符集(例如您当前使用的UTF-8)。