AES128 Decryption异常

昨日AES解密出现异常,有两种异常信息:
1.javax.crypto.badpaddingexception pad block corrupted
2.解决IllegalBlockSizeException:last block incomplete in decryption异常
在网上查询,原因可能如下:
1.如http://blog.csdn.net/yf210yf/article/details/7863066 中所说,但是我代码中已经是对结果进行过base64加解密的,所以该方案无效。

2.参考http://stackoverflow.com/questions/23491143/aes128-decryption-javax-crypto-badpaddingexception-pad-block-corrupted
对String常量存储的key直接进行getByte()可能会丢失信息,造成key不一致,所以解密失败
解决方案:
使用 SecureRandomsr=SecureRandom.getInstance("SHA1PRNG","SUN")

原获取SecretKeySpec代码如下:

    //如下该行可能出现丢失信息的情况
    byte[] keys = originalKey.getBytes(CHAR_SET);

        byte[] bytes = new byte[128 / 8];
        for (int i = 0; i < bytes.length; i++) {
            if (keys.length > i) {
                bytes[i] = keys[i];
            }else{
                bytes[i] = 0;
            }
        }

        return new SecretKeySpec(bytes, "AES");
    }

修改后获取SecretKeySpec代码如下:

        byte[] raw = null;
        try {
            byte[] keys = originalKey.getBytes(CHAR_SET);
            KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
            SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "SUN");
            sr.setSeed(keys);
            keyGenerator.init(128, sr);
            SecretKey skey = keyGenerator.generateKey();
             raw = skey.getEncoded();

        } catch (Exception e) {
            e.printStackTrace();
        }

        return new SecretKeySpec(raw, "AES");

你可能感兴趣的:(java)