//加密
public staticString encrypt(String content, String password) {try{//将秘钥补全为128位
KeyGenerator kgen = KeyGenerator.getInstance("AES");//若想改为DES加密,则需要将秘钥位数改为64位
kgen.init(128, newSecureRandom(password.getBytes()));
SecretKey secretKey=kgen.generateKey();byte[] enCodeFormat =secretKey.getEncoded();
SecretKeySpec key= new SecretKeySpec(enCodeFormat, "AES");//创建密码器
Cipher cipher = Cipher.getInstance("AES");byte[] byteContent = content.getBytes("utf-8");//初始化
cipher.init(Cipher.ENCRYPT_MODE, key);//加密
byte[] result =cipher.doFinal(byteContent);//Base64转码
returnBase64.encode(result);
}catch(NoSuchAlgorithmException e) {
e.printStackTrace();
}catch(NoSuchPaddingException e) {
e.printStackTrace();
}catch(InvalidKeyException e) {
e.printStackTrace();
}catch(UnsupportedEncodingException e) {
e.printStackTrace();
}catch(IllegalBlockSizeException e) {
e.printStackTrace();
}catch(BadPaddingException e) {
e.printStackTrace();
}return null;
}//解密
public static String decrypt(String content, String password) throwsException {try{//将秘钥补全为128位
KeyGenerator kgen = KeyGenerator.getInstance("AES");//若想改为DES加密,则需要将秘钥位数改为64位
kgen.init(128, newSecureRandom(password.getBytes()));
SecretKey secretKey=kgen.generateKey();byte[] enCodeFormat =secretKey.getEncoded();
SecretKeySpec key= new SecretKeySpec(enCodeFormat, "AES");//创建密码器
Cipher cipher = Cipher.getInstance("AES");//初始化
cipher.init(Cipher.DECRYPT_MODE, key);//Base64转码
byte[] encrypted1 =Base64.decode(content);//解密
byte[] result =cipher.doFinal(encrypted1);//二进制转为字符串
return new String(result, "utf-8");
}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;
}