簡體   English   中英

Android和Java-無法編碼-加密-解碼-解密字符串

[英]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”中。

我在日食中做了什么:

  1. 在Eclipse中打開根文件(.txt)(將文件拖放到編輯器中)
  2. 插入您的字符串或在文件中進行一些更改(空白字符)(在我的情況下為無法編碼的字符串)
  3. 按保存(CTLR + S),將出現一個對話框提示: SAVE AS UTF-8
  4. 刪除行
  5. 重新保存

另一種解決方案是在編輯時自動保存文件:

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".

來源: 如何在Eclipse中支持UTF-8編碼

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM