我正在使用Android javax API加密一个字符串,该字符串返回一个字节数组,我再次将其转换为String(目的是稍后写入文本文件)。
现在使用这个String,我转换为字节数组进行解密,返回另一个字节数组,我再次转换为String。
我无法让它发挥作用。我将问题缩小到字符串转换为字节数组部分。因为如果我使用加密的字节数组进行解密,然后获取它的工作字符串。
不确定是什么问题。我已使用以下内容进行转换:
String str;
Byte [] theByteArray = str.getBytes("UTF-8");
String val = new String (theByteArray , "UTF-8");
and
Byte [] theByteArray = str.getBytes();
String val = new String (theByteArray);
从字节数组转换为字符串的最佳方法是什么,反之亦然,而不会丢失任何内容?
提前致谢
答案 0 :(得分:3)
您可以使用apache库的Hex类。它提供decode和encode个功能。
String s = "42Gears Mobility Systems";
byte[] bytes = Hex.decodeHex(s.toCharArray());
String s2 = new String(Hex.encodeHex(bytes));
答案 1 :(得分:0)
如果你真的需要另一种方法将字节数组存储到字符串中,反之亦然,最好的方法是使用Base64 encoding,这样就不会丢失任何数据。这是您可以下载zip的link。解压缩zip并在项目中包含类文件。然后在需要编码和解码的任何地方使用以下代码片段。
//对数据进行编码并转换为字符串
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitMap.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte [] ba = bao.toByteArray();
String ba1=Base64.encodeBytes(ba);
//再次将数据解码为字节数组
try{
byte[] ba3 = Base64.decode(ba1);
}catch(Exception e)
{
}