Android 中使用java aes加密算法,报错信息android javax.crypto.BadPaddingException: pad block corrupted解决办法

今天,在Android 上面使用 AES 加密解密时,在解密处出现 javax.crypto.BadPaddingException: pad block corrupted 错误。
1.先上一个网上的 Java 可运行AES算法:来源

public static String AESEncode(String encodeRules,String content){
        try {
            //1.构造密钥生成器,指定为AES算法,不区分大小写
            KeyGenerator keygen=KeyGenerator.getInstance("AES");
            //2.根据ecnodeRules规则初始化密钥生成器
            //生成一个128位的随机源,根据传入的字节数组
            keygen.init(128, new SecureRandom(encodeRules.getBytes()));
              //3.产生原始对称密钥
            SecretKey original_key=keygen.generateKey();
              //4.获得原始对称密钥的字节数组
            byte [] raw=original_key.getEncoded();
            //5.根据字节数组生成AES密钥
            SecretKey key=new SecretKeySpec(raw, "AES");
              //6.根据指定算法AES自成密码器
            Cipher cipher=Cipher.getInstance("AES");
              //7.初始化密码器,第一个参数为加密(Encrypt_mode)或者解密解密(Decrypt_mode)操作,第二个参数为使用的KEY
            cipher.init(Cipher.ENCRYPT_MODE, key);
            //8.获取加密内容的字节数组(这里要设置为utf-8)不然内容中如果有中文和英文混合中文就会解密为乱码
            byte [] byte_encode=content.getBytes("utf-8");
            //9.根据密码器的初始化方式--加密:将数据加密
            byte [] byte_AES=cipher.doFinal(byte_encode);
          //10.将加密后的数据转换为字符串
            //这里用Base64Encoder中会找不到包
            //解决办法:
            //在项目的Build path中先移除JRE System Library,再添加库JRE System Library,重新编译后就一切正常了。
            String AES_encode=new String(new BASE64Encoder().encode(byte_AES));
          //11.将字符串返回
            return AES_encode;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        //如果有错就返加nulll
        return null;         
    }
    /* * 解密 * 解密过程: * 1.同加密1-4步 * 2.将加密后的字符串反纺成byte[]数组 * 3.将加密内容解密 */
    public static String AESDncode(String encodeRules,String content){
        try {
            //1.构造密钥生成器,指定为AES算法,不区分大小写
            KeyGenerator keygen=KeyGenerator.getInstance("AES");
            //2.根据ecnodeRules规则初始化密钥生成器
            //生成一个128位的随机源,根据传入的字节数组
            keygen.init(128, new SecureRandom(encodeRules.getBytes()));
              //3.产生原始对称密钥
            SecretKey original_key=keygen.generateKey();
              //4.获得原始对称密钥的字节数组
            byte [] raw=original_key.getEncoded();
            //5.根据字节数组生成AES密钥
            SecretKey key=new SecretKeySpec(raw, "AES");
              //6.根据指定算法AES自成密码器
            Cipher cipher=Cipher.getInstance("AES");
              //7.初始化密码器,第一个参数为加密(Encrypt_mode)或者解密(Decrypt_mode)操作,第二个参数为使用的KEY
            cipher.init(Cipher.DECRYPT_MODE, key);
            //8.将加密并编码后的内容解码成字节数组
            byte [] byte_content= new BASE64Decoder().decodeBuffer(content);
            /* * 解密 */
            byte [] byte_decode=cipher.doFinal(byte_content);
            String AES_decode=new String(byte_decode,"utf-8");
            return AES_decode;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }

        //如果有错就返加nulll
        return null;         
    }

这个算法很详细,对AES的加解密过程都做了注释,不过,在Android环境下,有小部分修改,BASE64Decoder类的使用需要自己添加依赖,我把它修改成android.util.Base64包,来解析Base64编码字符串,可以自行修改。

代码编译运行,此时,在AESDncode执行cipher.doFinal函数进行解密时,会报异常,出现android javax.crypto.BadPaddingException: pad block corrupted。

搜索了很多解决方案,大部分是修改SecureRandom

SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");

还有,将文本保存成十六进制字符,Base64字符等,相关转换代码如下:

public static String toHex(String txt) {  

        return toHex(txt.getBytes());  

    }  

    public static String fromHex(String hex) {  

        return new String(toByte(hex));  

    }  



    public static byte[] toByte(String hexString) {  

        int len = hexString.length()/2;  

        byte[] result = new byte[len];  

        for (int i = 0; i < len; i++)  

            result[i] = Integer.valueOf(hexString.substring(2*i, 2*i+2), 16).byteValue();  

        return result;  

    }  



    public static String toHex(byte[] buf) {  

        if (buf == null)  

            return "";  

        StringBuffer result = new StringBuffer(2*buf.length);  

        for (int i = 0; i < buf.length; i++) {  

            appendHex(result, buf[i]);  

        }  

        return result.toString();  

    }  

    private final static String HEX = "0123456789ABCDEF";  

    private static void appendHex(StringBuffer sb, byte b) {  

        sb.append(HEX.charAt((b>>4)&0x0f)).append(HEX.charAt(b&0x0f));  

    }  

这些方法并没有什么用,不知道与测试手机是否相关,本文使用的是三星S6 edge,最后找到的问题是,如果不使用KeyGenerator构造祕钥生成器就不会出现该异常,也就是说

            //1.构造密钥生成器,指定为AES算法,不区分大小写
            KeyGenerator keygen=KeyGenerator.getInstance("AES");
            //2.根据ecnodeRules规则初始化密钥生成器
            //生成一个128位的随机源,根据传入的字节数组
            keygen.init(128, new SecureRandom(encodeRules.getBytes()));
              //3.产生原始对称密钥
            SecretKey original_key=keygen.generateKey();
              //4.获得原始对称密钥的字节数组
            byte [] raw=original_key.getEncoded();

2.这部分代码构造的祕钥,在Android中出现了异常,修改了祕钥生成方式,最终在Android中成功运行。

public class AESHelper {
    /*** * AES key byte size,should be 16bytes,24bytes and 32bytes */
    public static final int KEY_BYTE_SIZE16 = 16;
    /*** * AES key byte size,should be 16bytes,24bytes and 32bytes */
    public static final int KEY_BYTE_SIZE24 = 24;
    /*** * AES key byte size,should be 16bytes,24bytes and 32bytes */
    public static final int KEY_BYTE_SIZE32 = 32;

    /*** * AES Key Generator * @param keyByteSize, key figures:16bytes,24bytes,32bytes * @return AES key string */
    public static String randomPassword(int keyByteSize) {
        String uuid = UUID.randomUUID().toString();
        int random = (int) (Math.random());
        return uuid.substring(random, random + keyByteSize);
    }

    /*** * AES Encrypt * @param encodeRules AES Key String,must be 128,192,256bits * @param content String to be encrypted * @return encrypted base64 string, if exception happens return null */
    public static String AESEncode(String encodeRules, String content) {
        try {
            byte[] rawKey = encodeRules.getBytes();
            SecretKeySpec skeySpec = new SecretKeySpec(rawKey, "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encrypted = cipher.doFinal(content.getBytes());
            return Base64.encodeToString(encrypted, DEFAULT);
        } catch (NoSuchAlgorithmException
                | NoSuchPaddingException
                | InvalidKeyException
                | IllegalBlockSizeException
                | BadPaddingException
                e) {
            e.printStackTrace();
        }
        return null;
    }

    /* * AES decrypt * @param encodeRules AES Key String,must be 128,192,256bits * @param content String to be decrypted * @return decrypted string, if exception happens return null */
    public static String AESDncode(String encodeRules, String content) {
        try {
            byte[] rawKey = encodeRules.getBytes();
            SecretKeySpec skeySpec = new SecretKeySpec(rawKey, "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            byte[] decrypted = cipher.doFinal(Base64.decode(content, DEFAULT));
            return new String(decrypted, "UTF-8");
        } catch (NoSuchAlgorithmException
                | NoSuchPaddingException
                | InvalidKeyException
                | IOException
                | IllegalBlockSizeException
                | BadPaddingException
                e) {
            e.printStackTrace();
        }
        return null;
    }
}

修改了祕钥生成方式,利用自定义16字节、24字节、32字节祕钥实现AES加解密功能。

点赞