同事的代码我拿来运行,他在他的电脑是可以的但是我的是不可以的,报异常了。报的异常 AES Encryption .BadPaddingException: Given final block not properly padded。
最后的解决问题是:
generator.init(128, new SecureRandom(miyao.getBytes()))
改成了
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(miyao.getBytes());
kgen.init(128, secureRandom);
原因:
如果new一个SecureRandom对象的话,在不同的操作系统中获取到算法是不同的,windows默认是SHA1PRNG,Linux的话是NativePRNG。所以调用时最好的方式便是调用getInstance 方法并在这之后调用 setSeed 方法。
最初的那种实现在 windows 上每次生成的 key 都相同,但是在部分linux 系统上则不同。
public SecureRandom(byte seed[]) {
super(0);
getDefaultPRNG(true, seed);
}
private void getDefaultPRNG(boolean setSeed, byte[] seed) {
String prng = getPrngAlgorithm();
if (prng == null) {
// bummer, get the SUN implementation
prng = "SHA1PRNG";
this.secureRandomSpi = new sun.security.provider.SecureRandom();
this.provider = Providers.getSunProvider();
if (setSeed) {
this.secureRandomSpi.engineSetSeed(seed);
}
} else {
try {
SecureRandom random = SecureRandom.getInstance(prng);
this.secureRandomSpi = random.getSecureRandomSpi();
this.provider = random.getProvider();
if (setSeed) {
this.secureRandomSpi.engineSetSeed(seed);
}
} catch (NoSuchAlgorithmException nsae) {
// never happens, because we made sure the algorithm exists
throw new RuntimeException(nsae);
}
}
// JDK 1.1 based implementations subclass SecureRandom instead of
// SecureRandomSpi. They will also go through this code path because
// they must call a SecureRandom constructor as it is their superclass.
// If we are dealing with such an implementation, do not set the
// algorithm value as it would be inaccurate.
if (getClass() == SecureRandom.class) {
this.algorithm = prng;
}
}
如果使用我最开始使用的方法(如下),我试着调试了一下,发现生成的key确实是不一致的。
generator.init(128, new SecureRandom(miyao.getBytes()))
显然如果用new的方式生成的key是不一样的。
我同事windows系统我是mac,所以运行会不一样。