问题
I'm trying to serialize an object (in this case a simple string), encrypt it, and write it to a file. The encryption seems to work, but the decryption always fails. I've tried searching around, but I can't seem to figure out what I'm doing wrong..
// Create a new key to encrypt and decrypt the file
byte[] key = "password".getBytes();
// Get a cipher object in encrypt mode
Cipher cipher = null;
try {
DESKeySpec dks = new DESKeySpec(key);
SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
SecretKey desKey = skf.generateSecret(dks);
cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, desKey);
} catch (InvalidKeyException | NoSuchAlgorithmException | InvalidKeySpecException | NoSuchPaddingException ex) {
System.err.println("[CRITICAL] Incryption chiper error");
}
// Encrypt the file
try {
new ObjectOutputStream(new CipherOutputStream(new FileOutputStream("test"), cipher)).writeObject("test text");
} catch (IOException e) {
System.err.println("[CRITICAL] Error encrypting data: " + e.getMessage());
e.printStackTrace();
}
// Get a cipher object in decrypt mode
try {
DESKeySpec dks = new DESKeySpec(key);
SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
SecretKey desKey = skf.generateSecret(dks);
cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, desKey);
} catch (InvalidKeyException | NoSuchAlgorithmException | InvalidKeySpecException | NoSuchPaddingException ex) {
System.err.println("[CRITICAL] Incryption chiper error");
}
// Decrypt the file
try {
// This is the line that throws the exception
System.out.println((String) new ObjectInputStream(new CipherInputStream(new FileInputStream("test"), cipher)).readObject());
} catch (IOException | ClassNotFoundException e) {
System.err.println("[CRITICAL] Error decrypting data: " + e.getMessage());
e.printStackTrace();
}
Running the above code results in the following exception:
[CRITICAL] Error decrypting data: null
java.io.EOFException
at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2304)
at java.io.ObjectInputStream$BlockDataInputStream.readUTFBody(ObjectInputStream.java:3042)
at java.io.ObjectInputStream$BlockDataInputStream.readUTF(ObjectInputStream.java:2843)
at java.io.ObjectInputStream.readString(ObjectInputStream.java:1617)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1338)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:369)
at Server.DataPersistence.main(DataPersistence.java:203)
Does anyone have any ideas?
Thanks!
回答1:
My guess is that nothing has been written to the file when you attempt to open and re-read the data back into your program. Try calling flush();
and then close();
on the output stream before attempting to read the file back in again.
来源:https://stackoverflow.com/questions/16390526/using-des-to-encrypt-and-decrypt-a-file-in-java