javax.crypto.BadPaddingException: Given final block not properly padded解決方案

JAVA的AES加密解密在windows上測試一切正常,上傳到空間上在解密時就出現錯誤。空間是Linux系統html

查看日誌發現出現此異常java

  javax.crypto.BadPaddingException: Given final block not properly paddedwindows

後面百度了一下終於解決了,在生成key的時候出現錯誤的dom

原來的代碼:post

複製代碼
private Key initKeyForAES(String key) throws NoSuchAlgorithmException {
        if (null == key || key.length() == 0) {
            throw new NullPointerException("key not is null");
        }
        SecretKeySpec key2 = null;try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128, new SecureRandom(key.getBytes()));
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            key2 = new SecretKeySpec(enCodeFormat, "AES");
        } catch (NoSuchAlgorithmException ex) {
            throw new NoSuchAlgorithmException();
        }
        return key2;

    }
複製代碼

主要是紅色部分的問題測試

修改後代碼:加密

複製代碼
private Key initKeyForAES(String key) throws NoSuchAlgorithmException {
        if (null == key || key.length() == 0) {
            throw new NullPointerException("key not is null");
        }
        SecretKeySpec key2 = null;
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        random.setSeed(key.getBytes());
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128, random);
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            key2 = new SecretKeySpec(enCodeFormat, "AES");
        } catch (NoSuchAlgorithmException ex) {
            throw new NoSuchAlgorithmException();
        }
        return key2;

    }
複製代碼

其實就是SecureRandom建立的方式不一樣而引發的錯誤,具體原理我也不懂,由於加密解密代碼都是網上搜的,具體沒研究過這個。總之能解決問題就好。url

我是從這找到解決方案的:http://wenku.baidu.com/link?url=wOibKHENi2Z5gFOL5prjGBE8RES1dZEZlrvfY1NTl89QJWtTwXUNLmgEXVYWGBGXR25oRvOKPJTI5M3o95KW0yIHwgFVEnJiZt1-0YvRQuaspa

隨心地記錄一些東西,以備不時之需。
相關文章
相關標籤/搜索