一、前言

最近和其它系统联调接口,用到了Java的AES加解密。

由其它系统AES加密,本人的系统获取到加密报文后,AES解密,获取到内容。

本来是比较简单的,可是其它系统只提供了秘钥,没有提供解密方法,解密方法需要我们自己写……

正常应该是加密方提供解密方法的吧,我觉得……

结果,只能自己找解密方法,解密过程中就报了2个错:

java.security.InvalidKeyException: Invalid AES key length: 14 bytes
javax.crypto.BadPaddingException: Given final block not properly padded

还好最后都解决了,在此记录下。

二、Invalid AES key length: 14 bytes的解决方法

1.出现这个错误,是秘钥长度不符合要求导致的。
例如,本人系统的代码如下:

    /**
     * 算法名称/加密模式/数据填充方式
     */
    private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";

    /**
     * AES加解密密钥(一般长度是16,但是其它系统给了个长度是14的秘钥)
     */
    private static final String KEY = "1234567890abcd";

    /**
     * AES
     */
    private static final String AES = "AES";
    
    /**
     * 解密方法
     */
    public static String decrypt(String encryptStr) {
        try {

            Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
            
            //这里用的秘钥KEY就是 1234567890abcd,然后就报错了:Invalid AES key length: 14 bytes
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(KEY.getBytes(), AES));

            //采用base64算法进行转码,避免出现中文乱码
            byte[] encryptBytes = Base64.decodeBase64(encryptStr);
            byte[] decryptBytes = cipher.doFinal(encryptBytes);
            return new String(decryptBytes);
        }catch (Exception e){
            log.error("decrypt({} , {})解密异常", encryptStr, decryptKey, e);
        }

        return null;
    }

这段会报错:cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(KEY.getBytes(), AES));
因为KEY的值是1234567890abcd,长度是14,所以报错:

java.security.InvalidKeyException: Invalid AES key length: 14 bytes

如果把秘钥改为1234567890abcdef,长度16,就没有问题了;

但是对面系统说他们就是用的长度14的秘钥加密的,所以不能这样解决。

2.虽然对面系统没有给解密方法,但是还好加密方法给截图发过来了。

分析了一波,发现对面系统先对秘钥进行了处理,转为了16位的,然后才加密;

所以解密方法需要这样写:

    /**
     * AES解密方法;秘钥长度是14,用secureRandom换成了16*8=128的秘钥
     */
    public static  String decryptTxx(String decryptStr) {
        try {

            KeyGenerator kgen = KeyGenerator.getInstance(AES);

            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            //这里,KEY="1234567890abcd",长度14
            secureRandom.setSeed(KEY.getBytes());

            kgen.init(128, secureRandom);
            SecretKey secretKey = kgen.generateKey();

            Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
            
            //这里,用转换后的秘钥,就没有问题了
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(secretKey.getEncoded(), AES));

            //采用base64算法进行转码,避免出现中文乱码
            byte[] encryptBytes = Base64.decodeBase64(decryptStr);
            byte[] decryptBytes = cipher.doFinal(encryptBytes);
            return new String(decryptBytes);
        }catch (Exception e){
            log.error("decryptTxx({} , {})解密异常", decryptStr, decryptKey, e);
        }

        return null;
    }

这样,用SecureRandom把长度14的秘钥转为了长度16的,然后解密,就没有问题了。

三、Given final block not properly padded的解决方法

报这个错误,可能是秘钥错误、解密失败导致的。

如上,使用秘钥1234567890abcdef解密、就会报这个错误;

需要使用秘钥1234567890abcd解密才行。

四、备注与完整加解密代码

1.报错Invalid AES key length: xx bytes,是秘钥长度不符合要求导致的(例如长度不是16),需要对秘钥进行转换,或者更换秘钥、使用符合长度的秘钥。

2.报错Given final block not properly padded,可能是秘钥错误、解密失败导致的,需要确认秘钥是否正确。

3.AES加解密完整代码如下:


import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;


/**
 * AES加解密
 */
public class AesEncryptUtils {
    private static Logger log = LoggerFactory.getLogger(AesEncryptUtils.class);

    /**
     * 算法名称/加密模式/数据填充方式
     */
    private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";

    /**
     * AES加解密默认密钥(16位,也可以用其它长度,那就用 New 方法 )
     */
    private static final String KEY = "1234567890abcdef";
    //private static final String KEY = "1234567890abcd";

    /**
     * AES
     */
    private static final String AES = "AES";


    /**
     * 加密
     * @param content 要加密的字符串
     * @param encryptKey 加密的密钥
     * @return
     * @throws Exception
     */
    public static String encrypt(String content, String encryptKey){
        try {
            KeyGenerator kgen = KeyGenerator.getInstance(AES);
            kgen.init(128);
            Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), AES));
            byte[] b = cipher.doFinal(content.getBytes("utf-8"));
            //采用base64算法进行转码,避免出现中文乱码
            return Base64.encodeBase64String(b);
        }catch (Exception e){
            log.error("encrypt({} , {})加密异常", content, encryptKey, e);
        }

        return null;
    }


    /**
     * 解密
     * @param encryptStr 要解密的字符串
     * @param decryptKey 要解密的密钥
     * @return
     * @throws Exception
     */
    public static  String decrypt(String encryptStr, String decryptKey) {
        try {
            Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(KEY.getBytes(), AES));

            //采用base64算法进行转码,避免出现中文乱码
            byte[] encryptBytes = Base64.decodeBase64(encryptStr);
            byte[] decryptBytes = cipher.doFinal(encryptBytes);
            return new String(decryptBytes);
        }catch (Exception e){
            log.error("decrypt({} , {})解密异常", encryptStr, decryptKey, e);
        }

        return null;
    }

    /**
     * AES解密方法;数据库里秘钥长度是14,用secureRandom换成了16*8=128的秘钥
     */
    public static  String decryptNew(String decryptStr, String decryptKey) {
        try {

            KeyGenerator kgen = KeyGenerator.getInstance(AES);

            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(decryptKey.getBytes());

            kgen.init(128, secureRandom);
            SecretKey secretKey = kgen.generateKey();

            Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(secretKey.getEncoded(), AES));

            //采用base64算法进行转码,避免出现中文乱码
            byte[] encryptBytes = Base64.decodeBase64(decryptStr);
            byte[] decryptBytes = cipher.doFinal(encryptBytes);
            return new String(decryptBytes);
        }catch (Exception e){
            log.error("decryptNew({} , {})解密异常", decryptStr, decryptKey, e);
        }

        return null;
    }

    public static  String encryptNew(String encryptStr, String encryptKey) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance(AES);

            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(encryptKey.getBytes());

            kgen.init(128,secureRandom);
            SecretKey secretKey = kgen.generateKey();

            Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(secretKey.getEncoded(), AES));
            byte[] b = cipher.doFinal(encryptStr.getBytes("utf-8"));
            //采用base64算法进行转码,避免出现中文乱码
            return Base64.encodeBase64String(b);
        }catch (Exception e){
            log.error("encryptNew({} , {})加密异常", encryptStr, encryptKey, e);
        }

        return null;
    }

    public static void main (String[] args) throws Exception{
        String str = "123";

        String encrypt = encrypt(str , KEY);
        System.out.println("加密后:" + encrypt);

        String decrypt = decrypt(encrypt , KEY);
        System.out.println("解密后:" + decrypt);

        String encrypt1 = encryptNew(str , KEY);
        System.out.println("加密后:" + encrypt1);

        String decrypt1 = decryptNew(encrypt1 , KEY);
        System.out.println("解密后:" + decrypt1);

    }

}

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐