50,530
社区成员
发帖
与我相关
我的任务
分享
private static String key = "12345678901234567890123456789012";
private static String mode = "AES/ECB/PKCS5Padding";
public static String decodeMsg(String msg) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException, InvalidKeySpecException {
Cipher cipher = Cipher.getInstance(mode);
cipher.init(Cipher.DECRYPT_MODE, getSecretKey(key));// 初始化
byte[] msgbyte = base64(msg);
byte[] result = cipher.doFinal(msgbyte);
return new String(result); // 解密
}
public static byte[] base64(String str) {
return Base64.getDecoder().decode(str);
}
private static SecretKeySpec getSecretKey(final String password) {
//返回生成指定算法密钥生成器的 KeyGenerator 对象
KeyGenerator kg = null;
try {
kg = KeyGenerator.getInstance("AES");
byte[] keyBytes = password.getBytes();
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(keyBytes);
//AES 要求密钥长度为 128
kg.init(128, secureRandom);
//生成一个密钥
SecretKey secretKey = kg.generateKey();
return new SecretKeySpec(secretKey.getEncoded(), "AES");// 转换为AES专用密钥
} catch (NoSuchAlgorithmException ex) {
//Logger.getLogger(AESUtil.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}