Java 读取加密文件
我正在编写一个应用程序,它将Java 读取加密文件,java,encryption,java-8,Java,Encryption,Java 8,我正在编写一个应用程序,它将员工列表加密到一个文本文件中。我能够将员工的列表加密为文本文件。当我试图解密它回来,我得到一些错误说 java.lang.ClassCastException:com.reading.employee.blueprint.employee不能强制转换为java.base/java.util.List 这是我正在处理的代码示例。 private static byte[] encryptingAFile(List<Employee> list) {
员工列表
加密到一个文本文件中。我能够将员工
的列表加密为文本文件。当我试图解密它回来,我得到一些错误说
java.lang.ClassCastException:com.reading.employee.blueprint.employee不能强制转换为java.base/java.util.List
这是我正在处理的代码示例。
private static byte[] encryptingAFile(List<Employee> list) {
byte[] empList, textEncrypted = null;
try {
ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
ObjectOutputStream object = new ObjectOutputStream(byteArray);
KeyGenerator keygenerator = KeyGenerator.getInstance("AES");
SecretKey myDesKey = keygenerator.generateKey();
Cipher desCipher;
desCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
String s;
for (Employee employee: list) {
object.writeObject(employee);
}
empList = byteArray.toByteArray();
desCipher.init(Cipher.ENCRYPT_MODE, myDesKey, new IvParameterSpec(new byte[16]));
textEncrypted = desCipher.doFinal(empList);
Files.write(Paths.get("Encrypt.txt"), textEncrypted);
desCipher.init(Cipher.DECRYPT_MODE, myDesKey, new IvParameterSpec(new byte[16]));
byte[] textDecrypted = desCipher.doFinal(textEncrypted);
ByteArrayInputStream bis = new ByteArrayInputStream(textDecrypted);
ObjectInputStream ois = new ObjectInputStream(bis);
List<Employee > result = (List<Employee>) ois.readObject();
System.out.println(result.toString());
}
catch (InvalidKeyException in) {
System.out.println(in);
}
catch (Exception e) {
System.out.println(e);
}
return textEncrypted;
}
私有静态字节[]加密文件(列表){
字节[]empList,textEncrypted=null;
试一试{
ByteArrayOutputStream byteArray=新建ByteArrayOutputStream();
ObjectOutputStream对象=新的ObjectOutputStream(byteArray);
KeyGenerator KeyGenerator=KeyGenerator.getInstance(“AES”);
SecretKey myDesKey=keygenerator.generateKey();
密码除颤器;
desCipher=Cipher.getInstance(“AES/CBC/PKCS5Padding”);
字符串s;
用于(员工:列表){
object.writeObject(员工);
}
empList=byteArray.toByteArray();
desCipher.init(Cipher.ENCRYPT_模式,myDesKey,新的IvParameterSpec(新字节[16]);
textEncrypted=desCipher.doFinal(empList);
file.write(path.get(“Encrypt.txt”)、textEncrypted);
desCipher.init(Cipher.DECRYPT_模式,myDesKey,新的IvParameterSpec(新字节[16]);
字节[]textDecrypted=desCipher.doFinal(textEncrypted);
ByteArrayInputStream bis=新的ByteArrayInputStream(文本解密);
ObjectInputStream ois=新ObjectInputStream(bis);
列表结果=(列表)ois.readObject();
System.out.println(result.toString());
}
捕获(InvalidKeyException-in){
系统输出打印项次(输入);
}
捕获(例外e){
系统输出打印ln(e);
}
返回加密文本;
}
我希望有人能帮助我。当您将对象写入
ObjectOutputStream
时,您一次只为每个员工编写一个对象,而不是编写一个列表对象。所以当你读回它们时,你不会得到一个列表对象。您需要首先将整个列表写入流,或者需要一次一个地读取员工
对象。是否有一个示例,您可以告诉我如何一次读取一个对象。我对java不太熟悉,这实际上是我第一次加密和解密文件。@William我要说的是,当你一次加密员工的一个时,你试图将对象解密为列表,这就是为什么你会得到ClassCastException。非常感谢你的提示。我照你说的做了,成功了!。