解决AES解密出现数据被截断的问题

AES/CBC/NoPadding加密后数据使用PKCS7Padding补码方式解密后出现数据被截断的问题

  • java不支持 PKCS7Padding补码方式
     

    public static String encrypt(String Data, String password){
        try {
                byte[] iv = DEFAULT_IV.getBytes(DEFAULT_CHARSET);
                Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
                int blockSize = cipher.getBlockSize();
                byte[] dataBytes = Data.getBytes(DEFAULT_CHARSET);
                int plaintextLength = dataBytes.length;
                if (plaintextLength % blockSize != 0) {
                    plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
                }
                byte[] plaintext = new byte[plaintextLength];
                System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
                IvParameterSpec ivspec = new IvParameterSpec(iv);
                cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(password), ivspec);
                byte[] encrypted = cipher.doFinal(plaintext);
                return Base64Utils.encodeToString(encrypted);//将cipher加密后的byte数组用base64编码生成字符串
            } catch (Exception e) {
            	logger.warn("【加密失败】明文:("+Data+") 密钥:"+password);
                e.printStackTrace();
                return null;
            }
    }
    //======================================================================
    public static void main(String[] args) throws Exception {
            String data = "abc";
            String passwordEnc = AESUtil.encrypt(data, "123456");//进行java的AES/CBC/NoPadding加密
            System.out.println(passwordEnc.length());
    }
    //======================================================================
    java.security.NoSuchAlgorithmException: Cannot find any provider supporting AES/CBC/PKCS7Padding
    	at javax.crypto.Cipher.getInstance(Cipher.java:535)

     

  • 不使用第三方库实现PKCS7Padding补码方式
     

        //此函数是pkcs7padding填充函数
        public static String pkcs7padding(String data) {
            int bs = 16;
            int padding = bs - (data.length() % bs);
            String padding_text = "";
            for (int i = 0; i < padding; i++) {
                padding_text += (char)padding;
            }
            return data+padding_text;
        }
    //======================================================================
    public static void main(String[] args) throws Exception {
            String data = "abc";
            data = AESUtil.pkcs7padding(data);
            String passwordEnc = AESUtil.encrypt(data, "123456");//进行java的AES/CBC/NoPadding加密
            System.out.println(passwordEnc.length());
    }
    //======================================================================
    加密之后的字符串:Gc9AmBtRpk7Z7Lv9C7JomA==

     

你可能感兴趣的:(AES)