序列化对象解密(和其他字节字段)期间的StreamCorruptedException

时间:2016-12-17 19:35:21

标签: java encryption serialization

我的软件在解密过程中引发了StreamCorruptedException: 我的密码是AES / CBC / PKCS5Padding,我的密钥是用PBKey Derivation方法获得的,所以我需要创建一个salt来生成AES128密钥。

我的目标是获得以这种方式形成的文件:

(我将删除异常管理代码以提高可读性) 我的密码:

char[] password = passwordString.toCharArray();

    SecureRandom random = new SecureRandom();
    byte salt[] = new byte[SALT_BYTES]; 
    random.nextBytes(salt);

    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");

    KeySpec keySpec = new PBEKeySpec(password, salt, ITERATION, AES_KEY_BITS);

    SecretKey tmp = factory.generateSecret(keySpec);

    SecretKey secretKey = new SecretKeySpec(tmp.getEncoded(), "AES");

    Cipher cipher = Cipher.getInstance("AES/CFB/PKCS5Padding");

    cipher.init(Cipher.ENCRYPT_MODE, secretKey);

    FileOutputStream fout = null;
    ObjectOutputStream objOut = null;


        fout = new FileOutputStream(PRIVATE_RING_FILENAME);

        fout.write(salt);

        byte[] ivN = cipher.getIV();
        fout.write(ivN);

        CipherOutputStream cos = new CipherOutputStream(fout, cipher);
        objOut = new ObjectOutputStream(cos);

        PrivateKeyRing prvKeyRing = new PrivateKeyRing();
        SealedObject sealedObject = new SealedObject(prvKeyRing, cipher);
        objOut.writeObject(sealedObject);

        fout.close();
        objOut.close();
        cos.close();

它没有问题。

我的解密代码:

char[] password = passwordString.toCharArray();

    File file = new File(PRIVATE_RING_FILENAME);
    FileInputStream fin = new FileInputStream(file);


    Cipher cipher = Cipher.getInstance("AES/CFB/PKCS5Padding");


    byte[] salt = new byte[SALT_BYTES];

    fin.read(salt);


    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");


    KeySpec keySpec = new PBEKeySpec(password, salt, ITERATION, AES_KEY_BITS);

    SecretKey = factory.generateSecret(keySpec);

    SecretKey secretKey = new SecretKeySpec(tmp.getEncoded(), "AES");


        byte[] ivN = new byte[AES_BYTES];
        fin.read(ivN, 0, AES_BYTES);

        cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(ivN));

    CipherInputStream cis = new CipherInputStream(fin, cipher);
    ObjectInputStream objIn;
    PrivateKeyRing prvKeyRing = null;
    SealedObject sealedObject = null;
    objIn = new ObjectInputStream(cis);

    sealedObject = (SealedObject) objIn.readObject();
    prvKeyRing = (PrivateKeyRing) sealedObject.getObject(cipher);

        objIn.close();
        fin.close();
        cis.close();

但StreamCorruptedException:无效的流标题:73720019在系统执行时发生:

objIn = new ObjectInputStream(cis);

如果我尝试编写对象而不加密所有作品。 你有什么想法? 当你尝试编写多个序列化对象时我读到了一些问题,但我认为情况并非如此。

1 个答案:

答案 0 :(得分:1)

这是因为您使用相同的密码加密和解密两次。首先用密码密封物体,然后将其写入密码输出流,密码处于密封物体的状态。这不会产生可以使用密码在其初始状态下解密的文件。您必须首先解开对象,然后从流中读取它,这是不可能的。摆脱密码流或密封对象。