那么解密方法这么写:
public static String decryptData(final String base64Data) throws Exception
{
final Cipher cipher = Cipher.getInstance(ALGORITHM_MODE_PADDING, "BC");
cipher.init(Cipher.DECRYPT_MODE, key);
return new String(cipher.doFinal(CyptoUtil.base64_decode_8859(base64Data).getBytes("ISO-8859-1")), "utf-8");
//注意:第一个是ISO-8859-1,第二个是utf-8
}
上面的CyptoUtil.base64_decode_8859的定义如下:
public static String base64_decode_8859(final String source)
{
String result = "";
final Base64.Decoder decoder = Base64.getDecoder();
try
{
result = new String(decoder.decode(source), "ISO-8859-1");
//此处的字符集是ISO-8859-1
}
catch (final UnsupportedEncodingException e)
{
e.printStackTrace();
}
return result;
}
对应地, 加密的方法这么写:
public static String encryptData(final String data) throws Exception
{
// 创建密码器
final Cipher cipher = Cipher.getInstance(ALGORITHM_MODE_PADDING, "BC");
// 初始化
cipher.init(Cipher.ENCRYPT_MODE, key);
return CyptoUtil.base64_encode_8859(new String(cipher.doFinal(data.getBytes()), "ISO-8859-1"));
}
上面的CyptoUtil.base64_encode_8859()定义如下:
public static String base64_encode_8859(final String source)
{
String result = "";
final Base64.Encoder encoder = Base64.getEncoder();
byte[] textByte = null;
try
{
textByte = source.getBytes("ISO-8859-1");
//注意此处的编码是ISO-8859-1
}
catch (final UnsupportedEncodingException e)
{
e.printStackTrace();
}
result = encoder.encodeToString(textByte);
return result;
}
(2),
第二种方法是: 不要用java 8 自带的java.util.Base64类, 而找一个其他人写好的Base64Util工具类
例如这个:
https://blog.csdn.net/m0_37218608/article/details/79505068
两种方法我个人推荐第一种, 毕竟是JAVA官方提供的,值得信赖!
本文主要想强调编码错误, 其余代码请参考:
https://blog.csdn.net/u010660575/article/details/76672402