gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 07:57:47 25 4
gpt4 key购买 nike

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

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

关于java - 使用DES在Java中加密和解密文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16390526/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com