AES加密遇到的问题(Java)

原码

SecureRandom ran = new SecureRandom(password.getBytes());
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128,ran);
SecretKey sK = kgen.generateKey();
byte[] enCodeF = sK.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeF, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, key);
return cipher.doFinal(src);

错误:javax.crypto.BadPaddingException: Given final block not properly padded. Such issues can arise if a bad key is used during decryption.

改正后的代码:

SecureRandom ran = SecureRandom.getInstance("SHA1PRNG");
ran.setSeed(password.getBytes());
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128,ran);
SecretKey sK = kgen.generateKey();
byte[] enCodeF = sK.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeF, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, key);
return cipher.doFinal(src);

指定算法名称(或者既指定算法名称又指定包提供程序),获取到唯一的随机数

  SecureRandom secureRandom = SecureRandom.getInstance( "SHA1PRNG" );

SecureRandom 实现完全随操作系统本身的內部状态,除非调用方在调用 getInstance 方法,然后调用 setSeed 方法;该实现在 windows 上每次生成的 key 都相同,但是在 solaris 或部分 linux 系统上则不同。

虽然我用的是windows系统,但使用了这个方法,问题确实解决了,不知道为什么。

参考地址:

https://blog.csdn.net/qq_38366063/article/details/102903547

https://blog.csdn.net/seapeak007/article/details/79747309

你可能感兴趣的:(学海无涯,java,eclipse)