读取加密文件

时间:2017-11-21 02:53:51

标签: java encryption java-8

我正在编写一个将Employee列表加密到文本文件中的应用程序。我能够将Employee列表加密为文本文件。当我尝试解密它时,我收到一些错误

  

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;
}

我希望有人可以帮助我。

1 个答案:

答案 0 :(得分:2)

当您将对象写入Employee时,您每次只编写一个Employee,您不会编写单个列表对象。因此,当您重新阅读它们时,您将无法获得单个列表对象。您需要首先将整个列表写入流中,或者您需要一次读取//service .ts export class Product { $prdKey: string; prdName: string; prdCat: string; //category prdSup: string; //supplier } deleteProduct(key: string) { this.productList.remove(key); } //component.ts onDelete($prdKey: string) { if (confirm('Are you sure to delete this record ?') == true) { this.ProductService.deleteProduct($prdKey); } }个对象。