我正在測試Java中的文本加密。問題是,我在行首開始出現一些奇怪的字符,我不明白爲什麼。當我刪除加密一切順利。Java CipherInputStream將奇怪的字符放在行首
當複製到記事本+ +,輸出的樣子:
Hello
<SOH>dear
<STX><STX>world
爲什麼會出現奇怪的控制字符?
代碼:
public class Test {
private static File file;
private static final byte[] STAT_KEY = { -1, -2, 3, 4, -5, -6, -7, 8 };
static {
file = new File("MyFile.txt");
}
private static Cipher getCipher(int mode) throws InvalidKeyException, NoSuchAlgorithmException,
InvalidKeySpecException, NoSuchPaddingException {
DESKeySpec dks = new DESKeySpec(STAT_KEY);
SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
SecretKey desKey = skf.generateSecret(dks);
Cipher cipher = Cipher.getInstance("DES");
cipher.init(mode, desKey);
return cipher;
}
private static void appendToFile(String item) throws Exception {
CipherOutputStream cos = null;
try {
cos = new CipherOutputStream(new FileOutputStream(file, true), getCipher(Cipher.ENCRYPT_MODE));
cos.write((item + String.format("%n")).getBytes());
} finally {
cos.close();
}
}
private static void readFromFile() throws Exception {
CipherInputStream cis = null;
try {
cis = new CipherInputStream(new FileInputStream(file), getCipher(Cipher.DECRYPT_MODE));
int content;
while ((content = cis.read()) != -1) {
System.out.print((char) content);
}
} finally {
cis.close();
}
}
public static void main(String[] args) throws Exception {
String[] items = { "Hello", "dear", "world" };
for (String item : items) {
appendToFile(item);
}
readFromFile();
}
}
PD:對不起,我處理異常:)
對於簡單的複製/粘貼示例爲+1。 – 2013-04-09 13:25:54
我編輯了你的問題,因爲當你看到記事本++解釋的控制字符時,它更容易理解。 – 2013-04-09 14:34:44
好的,謝謝你,對你們倆 – dalvarezmartinez1 2013-04-09 15:26:41