这两种方法用于加密/解密数据库内容:
public String encrypt(String str) {
try {
// Encode the string into bytes using utf-8
byte[] utf8 = str.getBytes("UTF8");
// Encrypt
byte[] enc = ecipher.doFinal(utf8);
// Encode bytes to base64 to get a string
return Base64.encodeToString(enc, Base64.NO_WRAP);
} catch (javax.crypto.BadPaddingException e) {
} catch (IllegalBlockSizeException e) {
} catch (UnsupportedEncodingException e) {
}
return null;
}
public String decrypt(String str) {
try {
// Decode base64 to get bytes
byte[] dec = Base64.decode(str, Base64.NO_WRAP);
// Decrypt
byte[] utf8 = dcipher.doFinal(dec);
// Decode using utf-8
return new String(utf8, "UTF8");
} catch (javax.crypto.BadPaddingException e) {
} catch (IllegalBlockSizeException e) {
} catch (UnsupportedEncodingException e) {
}
return null;
}
我已手动检查加密/解密的原始字节数组是否相同,但不知何故,CJK 字符串设法损坏。例如,韩语“유료컨텐츠는 63”会被乱码为. 我只能想到原文中的空格字符会搞砸一切……但这听起来很愚蠢。在机器人 Android 设备和 SQlite 浏览器 UI 上观察到相同的乱码。我整天都在摆弄 UTF 8 / 16,不认为它与手头的问题有关。乱码的结果在我看来仍然是韩国人......请提供任何提示?
编辑:这就是 utf8 字节数组在两种方法中的样子:
[0] -61 [195] [0xc3]
[1] -126 [130] [0x82]
[2] -27 [229] [0xe5]
[3] -116 [140] [0x8c]
[4] -125 [131] [0x83]
[5] -24 [232] [0xe8]
[6] -127 [129] [0x81]
[7] -124 [132] [0x84]
[8] -29 [227] [0xe3]
[9] -66 [190] [0xbe]
[10] -103 [153] [0x99]
[11] -26 [230] [0xe6]
[12] -108 [148] [0x94]
[13] -96 [160] [0xa0]
[14] 54 [0x36]
[15] 51 [0x33]