簡體   English   中英

使用DES加密和解密Java文件

[英]Using DES to encrypt and decrypt a file in Java

我正在嘗試序列化對象(在這種情況下為簡單字符串),對其進行加密,然后將其寫入文件。 加密似乎有效,但是解密總是失敗。 我曾嘗試四處搜尋,但似乎無法弄清楚自己在做什么。

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

有人有什么想法嗎?

謝謝!

我的猜測是,當您嘗試打開並將數據重新讀回程序時,沒有任何內容寫入文件。 嘗試調用flush(); 然后close(); 在嘗試再次讀回文件之前,先在輸出流上輸入內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM