java - 将 byte[] 转换为 String Java Android 加密

标签 java android encryption jncryptor

我正在使用 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/

相关文章:

java - 如何获取 Flux 的最后一项而不用 reduce() 或 last() 折叠它

java - @Where 与 @SecondaryTable 不适用于 Hibernate

java - Antlr4浮点解析

android - Card.io - Android 找不到 libcardioDecider.so

android - android 到 android 中的屏幕共享和 tem 查看器

c# - 安全发送/检索数据

java - 如何调用 onTouch() 方法

android - Geocoder.getFromLocation() 以阿拉伯语返回地址

java - 从 RSA 编码的 AES key 生成 AES key

php - Yii 2 替换 CSecurityManager 类