更新时间:2021-09-25 05:36:07
将加密数据存储在字符串中不是一个好主意,因为它们是用于人类可读的文本,而不是任意的二进制数据。对于二进制数据,***使用 byte []
。
It is not a good idea to store encrypted data in Strings because they are for human-readable text, not for arbitrary binary data. For binary data it's best to use byte[]
.
但是,如果必须这样做,您应该使用字节和字符之间具有 1对1映射的编码,也就是说,每个字节序列都可以映射到唯一的字符序列并返回。一个这样的编码是 ISO-8859-1 ,即:
However, if you must do it you should use an encoding that has a 1-to-1 mapping between bytes and characters, that is, where every byte sequence can be mapped to a unique sequence of characters, and back. One such encoding is ISO-8859-1, that is:
String decoded = new String(encryptedByteArray, "ISO-8859-1");
System.out.println("decoded:" + decoded);
byte[] encoded = decoded.getBytes("ISO-8859-1");
System.out.println("encoded:" + java.util.Arrays.toString(encoded));
String decryptedText = encrypter.decrypt(encoded);
其他不丢失数据的常见编码是十六进制和 base64 ,可惜你需要一个帮助程序库。标准API没有为他们定义类。
Other common encodings that don't lose data are hexadecimal and base64, but sadly you need a helper library for them. The standard API doesn't define classes for them.
使用UTF-16,程序将失败,原因有二:
With UTF-16 the program would fail for two reasons: