查到一般的写法是 利用了 SecureRandom
private static SecretKeySpec getSecretKey(final String key) { //返回生成指定算法密钥生成器的 KeyGenerator 对象 KeyGenerator kg = null;
try {
kg = KeyGenerator.getInstance(KEY_ALGORITHM);
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(key.getBytes("utf-8"));
kg.init(256, secureRandom);
//生成一个密钥
SecretKey secretKey = kg.generateKey();
// 转换为 AES 专用密钥
return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);
} catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) {
Logger.getLogger(AESUtil.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
不使用 SecureRandom 也能一句话默认生成 128 长度的
return new SecretKeySpec(key.getBytes("ASCII"), KEY_ALGORITHM);