Reputation: 241
I am writing an application that encrypts a list of Employee
into a text file. I was able to encrypt the Employee
s list to a text file. When I try to decrypt it back, I am getting some error saying
java.lang.ClassCastException: com.reading.employee.blueprint.Employee cannot be cast to java.base/java.util.List
This is an example of the code I am working on.
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;
}
I was hoping that someone could help me.
Upvotes: 1
Views: 38
Reputation: 60987
When you write the objects to the ObjectOutputStream
, you write each Employee
one at a time, you don't write a single list object. So when you read them back in, you don't get a single list object back. Either you need to write the whole list to the stream in the first place, or you need to read the Employee
objects back one at a time.
Upvotes: 2