Reputation: 1405
I'm testing the encryption of text in Java. The problem is that I get some strange characters at the beginning of the line and I don't understand why. When I remove encryption everything goes smoothly.
When copied into Notepad++, the output looks like:
Hello
<SOH>dear
<STX><STX>world
Why am I getting the strange control characters?
Code:
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: Excuse the way I deal with exceptions :)
Upvotes: 1
Views: 711
Reputation: 69369
Much like an ObjectOutputStream
, the CipherOutputStream
is not written in a way that allows direct appending.
append(data1) + append(data2) + append(data3) != append(data1+data2+data3)
You need to add your own method of delimiting different blocks of data. The funny ?
characters are the private control characters used by the CipherOutputStream
.
Life may be easier if you just encrypt the data normally (i.e. using a Cipher
object) and write the output to your file surrounded by suitable delimiters.
Upvotes: 1