Java ServerSocket receive sealed object

Description

Java ServerSocket receive sealed object

import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.KeyStore;
import java.security.PrivateKey;

import javax.crypto.SealedObject;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

//SealedObjectReceiver
public class Main {
   public static void main(String args[]) throws Exception {
      ServerSocket ss = new ServerSocket(6789);
      Socket s = ss.accept();// w ww  .  j  av  a  2  s. c o  m
      ObjectOutputStream out = new ObjectOutputStream(s.getOutputStream());

      ObjectInputStream in = new ObjectInputStream(s.getInputStream());

      char[] password = "123456".toCharArray();
      KeyStore ks = KeyStore.getInstance("JKS");
      ks.load(new FileInputStream("test.ks"), password);
      PrivateKey pri = (PrivateKey) ks.getKey("test", password);

      out.writeObject(ks.getCertificate("test"));

      SealedObject so = (SealedObject) in.readObject();
      byte[] bytes = (byte[]) so.getObject(pri);
      so = (SealedObject) in.readObject();
      SecretKey sk = new SecretKeySpec(bytes, 0, bytes.length, so.getAlgorithm());
      while (true) {
         System.out.println(so.getObject(sk));
         so = (SealedObject) in.readObject();
      }
   }
}



PreviousNext

Related