Java Socket send sealed object

Description

Java Socket send sealed object


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.security.PublicKey;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SealedObject;
import javax.crypto.SecretKey;

//SealedObjectSender
public class Main {
   public static void main(String args[]) throws Exception {
      Socket s = new Socket(args[0], 6789);
      ObjectInputStream in = new ObjectInputStream(s.getInputStream());
      ObjectOutputStream out = new ObjectOutputStream(s.getOutputStream());
      java.security.cert.Certificate c = (java.security.cert.Certificate) in.readObject();
      // authenticate the certificate c here
      PublicKey pub = c.getPublicKey();

      String alg = "DES";
      KeyGenerator kg = KeyGenerator.getInstance(alg);
      SecretKey sk = kg.generateKey();

      Cipher cipher = Cipher.getInstance(pub.getAlgorithm());
      cipher.init(Cipher.ENCRYPT_MODE, pub);
      SealedObject so = new SealedObject(sk.getEncoded(), cipher);
      out.writeObject(so);/*from w w  w  . ja  va2  s .  c  o  m*/

      cipher = Cipher.getInstance(alg);
      cipher.init(Cipher.ENCRYPT_MODE, sk);
      BufferedReader fromUser = new BufferedReader(new InputStreamReader(System.in));
      while (true) {
         so = new SealedObject(fromUser.readLine(), cipher);
         out.writeObject(so);
      }
   }
}



PreviousNext

Related