我正在使用 JNCryptor 库来加密字符串,然后将其作为加密字符串发送到我的服务器。这是我的代码:
String teststring = "Hello World";
JNCryptor cryptor = new AES256JNCryptor();
byte[] plaintext = teststring.getBytes();
String password = "test";
try {
byte[] ciphertext = cryptor.encryptData(plaintext, password.toCharArray());
String a = new String(ciphertext);
return a;
} catch (CryptorException e) {
// Something went wrong
e.printStackTrace();
return "0";
}
但是,当我将字符串“a”发送到服务器时,它有一堆无法识别的字符。我读过an explanation 关于此:
String is not a suitable container for binary data and ciphertext is binary data. For any given character encoding not all bytes and byte sequences represents characters and when an un-representable byte or sequence is found it is converted to some error character. Obviously this error character cannot be converted back to a unique byte or byte sequence (it is a many->one mapping).
这个建议正确吗?那么,如何正确地将 byte[] 转换为字符串呢?这样我就可以将其可读地存储在我的服务器上?
最佳答案
没有从字节数组转换为字符串的标准方法。您必须对字节数组进行编码。执行此操作的常见方法是 Base64 编码。 有关 Base64 编码如何工作的说明:http://en.wikipedia.org/wiki/Base64
然后,一旦它到达您的服务器,base64 将其解码回原始字节数组并存储它,完成!
关于java - 将 byte[] 转换为 String Java Android 加密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24894477/