AES为对称加密,即加密解密用同一个密钥。
AES加密
/**
* AES加密
*
* @param content 需要加密的内容
* @param password 加密密钥
* @return
*/
public static byte[] AESencrypt(String content, String password) {
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128, new SecureRandom(password.getBytes()));
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFromat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFromat, "AES");
Cipher cipher = Cipher.getInstance("AES");//创建密码器
byte[] byteContent = content.getBytes("utf-8");
cipher.init(Cipher.ENCRYPT_MODE, key);//初始化
byte[] result = cipher.doFinal(byteContent);
return result;//加密
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}
AES解密
/**
* AES解密
*
* @param content 需要解密的内容
* @param password 解密密钥
* @return
*/
public static byte[] AESdecrypt(byte[] content, String password) {
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128, new SecureRandom(password.getBytes()));
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFromat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFromat, "AES");
Cipher cipher = Cipher.getInstance("AES");//创建密码器
cipher.init(Cipher.DECRYPT_MODE, key);//初始化
// byte[] byteContent = content.getBytes("utf-8");
byte[] result = cipher.doFinal(content);
// String s = new String(result,"utf-8");
return result;
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}