2012-09-01 3 views
5

文字列の配列リストを暗号化してファイルに格納する必要があります。そして、ファイルの内容を解読し、それらをアレイリストに復元します。しかし、私はコンテンツを解読すると、 'Null'のブロックがコンテンツの中にあります。 'Null'ブロックがない場合、テキストの残りはiと同じです。ArrayListの暗号化と復号化<String>

public static void encryptFile(List<String> moduleList, File fileOut) { 
    try { 
     OutputStream out = new FileOutputStream(fileOut); 
     out = new CipherOutputStream(out, encryptCipher); 
     StringBuilder moduleSet = new StringBuilder(); 
     for (String module : moduleList) { 
      moduleSet.append(module + "#"); 
     } 
     out.write(moduleSet.toString().getBytes(Charset.forName("UTF-8"))); 
     out.flush(); 
     out.close(); 
    } catch (java.io.IOException ex) { 
     System.out.println("Exception: " + ex.getMessage()); 
    } 
} 

public static List<String> decryptFile(File fileIn) { 
    List<String> moduleList = new ArrayList<String>(); 
    byte[] buf = new byte[16]; 

    try { 
     InputStream in = new FileInputStream(fileIn); 
     in = new CipherInputStream(in, decryptCipher); 

     int numRead = 0; 
     int counter = 0; 
     StringBuilder moduleSet = new StringBuilder(); 
     while ((numRead = in.read(buf)) >= 0) { 
      counter++; 
      moduleSet.append(new String(buf)); 
     } 

     String[] blocks = moduleSet.split("#"); 
     System.out.println("Items: " + blocks.length); 

    } catch (java.io.IOException ex) { 
     System.out.println("Exception: " + ex.getMessage()); 
    } 
    return moduleList; 
} 

文字列はUTF-16でJavaでエンコードされているので、私はUTF-16で試してみました、しかし、それだけで最悪の出力になります。 あなたの提案は、私はあなたが文字列にしてから、リストの内容を変換するコードをリッピングし、ObjectOutputStreamでそれに代わる... おかげ

+6

ソースコードの写真を撮ったり投稿したりしないでください。ソースコードをコピーして質問に貼り付けるか、時間をかけて入力してください。 – Jeffrey

+0

問題は(242、137)の位置にある可能性があります。 – Alex

+1

@Jeffrey可能であれば、私はコピー/貼り付けに行きます。私が「Kindle」などで利用できなかった場合は、デスクトップ開発マシンに戻るまで質問を遅らせることになるでしょう。コードを入力し直す際にエラーが多すぎます。 –

答えて

4

を理解されるであろう。

FileOutputStream out1 = new FileOutputStream(fileOut); 
CipherOutputStream out2 = new CipherOutputStream(out1, encryptCipher); 
ObjectOutputStream out3 = new ObjectOutputStream(out2); 
out3.writeObject(moduleList); 

その後、読むために戻る:

FileInputStream in1 = new FileInputStream(fileIn); 
CipherInputStream in2 = new CipherInputStream(in1, decryptCipher); 
ObjectInputStream in3 = new ObjectInputStream(in2); 
moduleList = (Set<String>)in3.readObject() 
+0

はい、それは働いた。あなたの方法を使用することによって、それはリスト内の各文字列を通過して送信する必要はありません。だから、私はエンコードのことについて全く考慮する必要はありません。私はそれをオブジェクトとして送り、それを簡単に読むことができます。相当な量のコード行を削減します。ありがとう – Anuruddha