Linux下运行java AES解密失败,报 javax.crypto.BadPaddingException: Given final block not properly padded.

AES 加密、解密源码见另一篇博客:https://blog.csdn.net/weixin_43276786/article/details/90288171

 

在windows下运行正常,对加密后的密文可以正常解密,

但是放到linux上运行,则报错,错误信息如下

Linux下运行java AES解密失败,报 javax.crypto.BadPaddingException: Given final block not properly padded._第1张图片

原因:

经过检查之后,定位在生成KEY的方法上,即如下红色代码:

public static Cipher getCipher(int model) throws Exception{
            //1.获取加密生成器
            KeyGenerator keygen=KeyGenerator.getInstance("AES");
            //2.根据ecnodeRules规则初始化密钥生成器
            //生成一个128位的随机源,根据传入的字节数组
           keygen.init(128, new SecureRandom(RANDOM_KEY.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(model, key);
            return cipher;
    }

SecureRandom 实现完全随操作系统本身的內部状态,除非调用方在调用 getInstance 方法,然后调用 setSeed 方法;该实现在 windows 上每次生成的 key 都相同,但是在 solaris 或部分 linux 系统上则不同。关于SecureRandom类的详细介绍,见 http://yangzb.iteye.com/blog/325264
 

解决办法

把原来的getCipher方法中红色改为如下的红色部分:

public static Cipher getCipher(int model) throws Exception{
            //1.获取加密生成器
            KeyGenerator keygen=KeyGenerator.getInstance("AES");
            //2.根据ecnodeRules规则初始化密钥生成器
            //防止linux下 随机生成key
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(RANDOM_KEY.getBytes());
            keygen.init(128, secureRandom);

            //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(model, key);
            return cipher;
    }

 

你可能感兴趣的:(加密,解密)