58,453
社区成员
发帖
与我相关
我的任务
分享
/**
* 加密数据
* @param content 需要加密的内容
* @param password 加密密码
* @return
*/
public static byte[] encryptForAES(byte[] content, String password) {
if(content == null || content.length == 0 || password == null) return null;
try {//不需要这么复杂的key
//KeyGenerator kgen = KeyGenerator.getInstance("AES");
//kgen.init(128, new SecureRandom(password.getBytes("utf-8")));
//SecretKey secretKey = kgen.generateKey();
//byte[] enCodeFormat = secretKey.getEncoded();
byte[] enCodeFormat = getBytesForUTF8(password);
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");// 创建密码器,ECB模式,PKCS5Padding填充方式 AES/ECB/PKCS5Padding
cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化为加密模式
byte[] result = cipher.doFinal(content);
return result; // 加密
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}