当在另一个类中创建对象时,如何通过ObjectOutputStream编写对象?

时间:2015-05-31 20:50:48

标签: java encryption inputstream outputstream

我试图总结一下我的问题,但实际上还有更多的问题。对于uni的任务,我们应该创建两个构造函数(英语不是我的第一语言)

1)public SecureInputStream(InputStream base,OutputStream remote)

2)public SecureOutputStream(OutputStream base,InputStream remote)

1)应该创建BigIntegers g,n,k然后生成一个公钥 K=g^k mod n,然后通过遥控器向另一方发送gnk,然后假设读取其他方k并创建秘密s= k^k mod n并使用它启动随机生成器。我应该覆盖 write(int b),所以write会使用BigInteger类中的xor方法加密s,然后通过remote将它发送到另一端。

2)应该从1)等待g.n,创建它自己的k然后通过远程发回它。构造函数还将使用秘密s

启动随机生成器

我们的讲师给了我们两个“简单”类客户端和服务器,它们使用Socket,Port Situation。我的问题是,每个类都有自己的输入/输出流来读/写一些东西。我如何介于两者之间,更重要的是,一旦读完就会发送到陆地的信息?我所做的两天都是在线阅读和观看教程。我已经明白了什么是流,虽然我不能真正理解它们是如何工作的。

如何通过该流发送多个内容?对方怎么知道我发送的是哪一个?我如何发送一般的东西?

我希望有人可以帮助我。那么这是我到目前为止的代码,主要方法来自我们的讲师。想象一下,我做了所有的进口。

//Error Method: Invalid method declaration, return type missing,
//I'm guessing the constructor needs to sit in a class called 
//SecureInputStream, but how can I use the stuff in the class Client
//when the constructor I need is in another?

public SecureInputStream(InputStream base, OutputStream remote) {
    super();
    //g,n,k,s are created 
    BigInteger g = BigInteger.probablePrime(1024, new SecureRandom());
    BigInteger n = BigInteger.probablePrime(1024, new SecureRandom());
    BigInteger k = BigInteger.probablePrime(1024, new SecureRandom());
    BigInteger s = BigInteger.probablePrime(1024, new SecureRandom());
    Random r = new Random();
    r.nextInt();
    BigInteger exponent1 = new BigInteger("r");
    BigInteger exponent2 = new BigInteger("k");
    k = g.modPow(exponent1, n);
    s = k.modPow(exponent2, n);

}

public static void main(String... args) {

    Socket server = null;

    try {
        // Connect to server on local machine ("localhost") and port 3145.
        server = new Socket("localhost", 3145);

        // Get input stream from server and read its message
        Scanner in = new Scanner(server.getInputStream());
        // If we need to send messages to the server:
        // OutputStream out = server.getOutputStream();

        while (in.hasNext()) {
            System.out.println(in.nextLine());
        }
        in.close();

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (server != null) {
                server.close();
            }
        } catch (IOException e) {

        }
    }
}

1 个答案:

答案 0 :(得分:1)

  

如何通过ObjectOutputStream,

编写对象

您致电ObjectOutputStream.writeObject().

  • 第二个问题,你没有问:我如何通过ObjectInputStream
  • 阅读对象

您致电ObjectInputStream.readObject().

  • 第3个问题,你没有问:我怎样才能发现传入对象的类型?

您可以通过instanceof运算符发现收到的对象的类型。但是对于大多数协议,包括您描述的协议,您不需要这样做。协议通常定义什么时候发送,所以你要做的就是相应地阅读。

  

何时在另一个类中创建对象?

创建对象的位置没有任何区别。

相关问题