解密一个加密的.ser文件,抛出StreamCorruptedException

时间:2017-01-29 20:01:26

标签: java encryption serialization cryptography

我正在创建一个.ser文件,其中包含加密字符串的映射及其解密密钥。(我意识到这不是最好的方法,但我需要显示项目的不同加密方法)然后加密序列化使用:

private void encryptKeysFile() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, IOException{
    SecretKey key64 = new SecretKeySpec( new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 }, "Blowfish" );
    Cipher cipher = Cipher.getInstance( "Blowfish" );
    cipher.init( Cipher.ENCRYPT_MODE, key64 );
    File keysFile = new File(System.getProperty("src"),fileName);
    SealedObject sealedObject = new SealedObject(keysFile, cipher);
    CipherOutputStream cipherOutputStream = new CipherOutputStream( new BufferedOutputStream( new FileOutputStream(fileName) ), cipher );
    ObjectOutputStream outputStream = new ObjectOutputStream( cipherOutputStream );
    outputStream.writeObject(sealedObject);
    outputStream.close();
}

然后将对象写回驱动器上的文件。 读者文件的另一种方法是解密它:

private File dencryptKeysFile() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, IOException, ClassNotFoundException, BadPaddingException{
    SecretKey key64 = new SecretKeySpec( new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 }, "Blowfish" );
    Cipher cipher = Cipher.getInstance( "Blowfish" );
    cipher.init( Cipher.DECRYPT_MODE, key64 );
    CipherInputStream cipherInputStream = new CipherInputStream(new BufferedInputStream(new FileInputStream(fileName)),cipher);
    ObjectInputStream inputStream = new ObjectInputStream(cipherInputStream);
    SealedObject sealedObject = (SealedObject)inputStream.readObject();
    inputStream.close();

    File keysFile =(File)sealedObject.getObject(cipher);
    this.keysFile = keysFile;
    return keysFile;
}

运行这些方法时出现错误:

java.io.StreamCorruptedException: invalid stream header: E0F0DDB8
at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
at java.io.ObjectInputStream.<init>(Unknown Source)
at mainClasses.Encrypter.dencryptKeysFile(Encrypter.java:180)
at mainClasses.Encrypter.main(Encrypter.java:214)

抛出的文件未被读取。 Encrypter.java:180 = ObjectInputStream inputStream = new ObjectInputStream(cipherInputStream);

1 个答案:

答案 0 :(得分:1)

您正在密封,然后使用相同的Cipher加密,这意味着加密发生在密封后状态的Cipher,然后您正在解密并开启另一个Cipher },但是这一次当然<script src="cellComponent.js"></script>处于初始状态,而不是后密封状态,它只有在去密封后才能达到,这种情况永远不会发生。

你在这里使用腰带和背带。您不需要密封和密码流加密。使用其中一种。