[英]Android and Java - Unable to encode - encrypt - decode - decrypt string
我的桌面應用程序(用Java編寫)為Android應用程序加密了文件。
整個文件中的字符串部分:
...“ 一個kerékpár(vagy bicikli)egy emberierővelhajtottkétkerekűjármű。19.századikifejlesztése ” ...
從文件讀取:
FileInputStream is = new FileInputStream("cycles.txt");
StringBuilder sb = new StringBuilder();
Charset inputCharset = Charset.forName("ISO-8859-1");
BufferedReader br = new BufferedReader(new InputStreamReader(is, inputCharset));
String read;
while((read=br.readLine()) != null) {
sb.append(read);
}
讀取整個文件后,我將其加密:
String text = sb.toString();
Encrypter er = new Encrypter();
byte[] bEncrypt = er.encrypt(text);
加密后,我將其編碼為base64:
bEncrypt = Base64.getEncoder().encode(bEncrypt);
text = new String(bEncrypt, "ISO-8859-1");
之后,文件將保存在我的PC磁盤上:
File file = new File(System.getProperty("user.dir") + "/files/encr_cycles.txt");
try {
PrintWriter pr = new PrintWriter(new FileWriter(file));
pr.print(text);
pr.close();
} catch (IOException e) {
e.printStackTrace();
}
我從Android應用程序讀取了文件:
BufferedReader reader = new BufferedReader(new InputStreamReader(getAssets().open("files/encr_cycles.txt"), "ISO-8859-1"));
// Read line by line
String mLine;
StringBuilder sb = new StringBuilder();
while ((mLine = reader.readLine()) != null) {
sb.append(mLine);
}
解碼和解密:
byte[] dec = Base64.decode(encryptedText, Base64.DEFAULT);
byte[] data= new Decipher().doFinal(dec);
String text= new String(data, "ISO-8859-1");
給定的文本是:
“ 一個kerékpár(vagy bicikli)的埃及人嗎?vel hajtottkétkerek?járm?。19.századikifejlesztése ”
注意“?” 在字符串中? 有些字符未正確解碼。
Q1:我做錯了什么?
Q2:我使用了錯誤的字符集嗎?
我在所有應用程序(台式機和移動設備)上將字符集更改為“ UTF-8”。 問題出在根文件上。 該文件未保存在“ UTF-8”中。
我在日食中做了什么:
另一種解決方案是在編輯時自動保存文件:
Window > Preferences > General > Content Types, set UTF-8 as the default
encoding for all content types.
Window > Preferences > General > Workspace, set "Text file encoding" to "Other : UTF-8".
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.