Anu*_*dha 5 java encryption file-io aes
我需要通过加密来存储文件中的数组字符串列表.然后我解密文件内容并将它们恢复到数组列表.但是当我解密内容时,内容中会出现'Null'块.没有'Null'块,其余文本与i编码相同.
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;
}
Run Code Online (Sandbox Code Playgroud)
我尝试使用UTF-16,因为字符串是用UTF-16编写的,但它只会使输出最差.您的建议将不胜感激...谢谢
小智 4
我将删除将列表内容与字符串相互转换的代码,并将其替换为ObjectOutputStream:
FileOutputStream out1 = new FileOutputStream(fileOut);
CipherOutputStream out2 = new CipherOutputStream(out1, encryptCipher);
ObjectOutputStream out3 = new ObjectOutputStream(out2);
out3.writeObject(moduleList);
Run Code Online (Sandbox Code Playgroud)
然后,回读:
FileInputStream in1 = new FileInputStream(fileIn);
CipherInputStream in2 = new CipherInputStream(in1, decryptCipher);
ObjectInputStream in3 = new ObjectInputStream(in2);
moduleList = (Set<String>)in3.readObject()
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2193 次 |
最近记录: |