ObjectInputStream上的java.io.StreamCorruptedException,同时将它封装在Java中的CipherInputStream中

我通过套接字(单个客户端单个服务器)发送加密对象。客户端将加密对象作为密封对象发送,服务器将对象解密。但是在服务器端创建ObjectInputStream的过程中,它抛出了StreamCorruptedException异常。 我在网上搜了很多,我的代码看起来很好,但我不知道为什么抛出异常。ObjectInputStream上的java.io.StreamCorruptedException,同时将它封装在Java中的CipherInputStream中

这里是Client类:

package sample; 

import javax.crypto.Cipher;

import javax.crypto.CipherOutputStream;

import javax.crypto.SealedObject;

import javax.crypto.spec.SecretKeySpec;

import java.io.ObjectOutputStream;

import java.net.Socket;

public class Client {

private static Socket socket;

public static void main(String args[]) throws Exception {

socket=new Socket("127.0.0.1",7777);

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

SecretKeySpec sks = new SecretKeySpec("MyDifficultPassw".getBytes(), "AES");

cipher.init(Cipher.ENCRYPT_MODE, sks);

CipherOutputStream cos=new CipherOutputStream(socket.getOutputStream(),cipher);

ObjectOutputStream oos=new ObjectOutputStream(cos);

oos.flush();

SealedObject sealedObject=new SealedObject("SampleString",cipher);

oos.writeObject(sealedObject);

}

}

这里是我的服务器类:

package sample; 

import javax.crypto.Cipher;

import javax.crypto.CipherInputStream;

import javax.crypto.CipherOutputStream;

import javax.crypto.SealedObject;

import javax.crypto.spec.SecretKeySpec;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

import java.net.ServerSocket;

import java.net.Socket;

public class Server {

private static ServerSocket serverSocket;

public static SecretKeySpec sks;

public static void main(String args[]) throws Exception{

serverSocket=new ServerSocket(7777);

Socket clientSocket=serverSocket.accept();

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

sks = new SecretKeySpec("MyDifficultPassw".getBytes(), "AES");

cipher.init(Cipher.DECRYPT_MODE, sks);

CipherInputStream cis=new CipherInputStream(clientSocket.getInputStream(),cipher);

ObjectInputStream ois=new ObjectInputStream(cis); //line 23

SealedObject so=(SealedObject) ois.readObject();

System.out.println((String)so.getObject(cipher));

}

}

及以下异常被抛出就当客户端连接服务器端:

Exception in thread "main" java.io.StreamCorruptedException: invalid stream header: 73720019 

at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:857)

at java.io.ObjectInputStream.<init>(ObjectInputStream.java:349)

at sample.Server.main(Server.java:23)

回答:

问题是双重加密。输出案例中的密码必须密封对象,然后对流进行加密,但输入案例中的密码对象必须解密流,然后开封对象,这是相反的顺序。

删除SealedObject或密码流。

以上是 ObjectInputStream上的java.io.StreamCorruptedException,同时将它封装在Java中的CipherInputStream中 的全部内容, 来源链接: utcz.com/qa/261005.html

回到顶部