我正在创建一个 .ser 文件,其中包含加密字符串及其解密 key 的映射。(我意识到这不是最好的方法,但我需要显示项目的不同加密方法)然后我对序列化的序列进行加密使用:
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)
在文件未被读取时抛出。
加密器.java:180 = ObjectInputStream inputStream = new ObjectInputStream(cipherInputStream);
最佳答案
您正在使用相同的Cipher
进行密封然后加密,这意味着加密是在密封后状态下使用Cipher
进行的,然后您正在解密和解封与另一个Cipher
,但是这次Cipher
当然处于初始状态,而不是解封后状态,它只能在解封后才能达到,这永远不会发生。
您在这里使用腰带和背带。您不需要同时进行密封和密码流加密。使用其中之一。
关于java - 解密加密的 .ser 文件并抛出 StreamCorruptedException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41925353/