使用DES在Java中加密和解密文件

时间:2013-05-06 00:28:35

标签: java serialization des

我正在尝试序列化一个对象(在本例中是一个简单的字符串),对其进行加密,然后将其写入文件。加密似乎有效,但解密总是失败。我试过四处寻找,但我似乎无法弄清楚我做错了什么..

// 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();
}

运行上面的代码会导致以下异常:

[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)

有没有人有任何想法?

谢谢!

1 个答案:

答案 0 :(得分:5)

我的猜测是,当您尝试打开并重新将数据重新读回程序时,没有任何内容写入文件。在尝试再次读回文件之前,请尝试在输出流上调用flush();然后调用close();