我正在研究一个跨平台的加密系统。要求之一是轻松加密和解密应用程序代码中的字符串。
加密类完美无缺,但我在 java 端的字符串编码有问题。
目前,我有以下静态方法:
public static String encrypt(String key, String data)
{
byte[] decoded_key;
byte[] decoded_data;
try
{
decoded_key = key.getBytes("UTF-8");
decoded_data = data.getBytes("UTF-8");
}
catch (Exception e)
{
//Not Supposed to happen.
throw new RuntimeException();
}
if(decoded_key.length != 16)
throw new IllegalArgumentException("Key length must be of 16 bytes. Given is " + decoded_key.length + ".");
try
{
return(IOUtils.toString(encrypt(decoded_key, decoded_data), "UTF-8"));
}
catch (Exception e)
{
//Not Supposed to happen.
throw new RuntimeException();
}
}
public static String decrypt(String key, String data)
{
byte[] decoded_key;
byte[] decoded_data;
try
{
decoded_key = key.getBytes("UTF-8");
decoded_data = data.getBytes("UTF-8");
}
catch (Exception e)
{
//Not Supposed to happen.
throw new RuntimeException();
}
if(decoded_key.length != 16)
throw new IllegalArgumentException("Key length must be of 16 bytes. Given is " + decoded_key.length + ".");
try
{
return(IOUtils.toString(decrypt(decoded_key, decoded_data), "UTF-8"));
}
catch (Exception e)
{
//Not Supposed to happen.
throw new RuntimeException();
}
}
解密时我的单元测试失败。我进行了一项测试,将编码 UTF-8 数据的字节数组encoded_data
与IOUtils.toString(
encode_data, "UTF-8").getBytes("UTF-8")
进行了比较,由于某种原因,它们完全是不同的数组。难怪我的解密算法失败了。
从 java 字符串转换为 UTF-8 字节数组并转换回 java 字符串的正确过程是什么?