private static PublicKey receivePublicKey(final DataInputStream in) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException { final byte[] keyBytes = new byte[in.readInt()]; in.readFully(keyBytes); final KeyFactory kf = KeyFactory.getInstance(KeyExchange.DH.value()); final X509EncodedKeySpec x509Spec = new X509EncodedKeySpec(keyBytes); final PublicKey theirPublicKey = kf.generatePublic(x509Spec); return theirPublicKey; }
private static void generateSecretValue(final PublicKey theirPublicKey) throws NoSuchAlgorithmException, InvalidKeyException { final KeyAgreement ka = KeyAgreement.getInstance(KeyExchange.DH.value()); ka.init(keyPair.getPrivate()); ka.doPhase(theirPublicKey, true); secret = ka.generateSecret(); // LOG.info(MessageFormat.format("Secret value generated by SkipClient:{0}", new // String(Base64.encodeBase64(secret)), "UTF-8")); }
public static void start() throws IOException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeySpecException, InvalidKeyException { // Create a Diffie-Hellman Key pair final KeyPairGen kpg = new KeyPairGen(KeyExchange.DH.value(), Skip.sDHParameterSpec); keyPair = kpg.getKeyPair(); // Open the network connection LOG.info("Connecting to Server:" + host + ":" + port); final Socket s = new Socket(host, port); LOG.info("Connected!"); final DataOutputStream out = new DataOutputStream(s.getOutputStream()); final DataInputStream in = new DataInputStream(s.getInputStream()); sendPublicKey(out); LOG.info("Public key sent to server."); final PublicKey theirPublicKey = receivePublicKey(in); LOG.info("Public key received from server."); generateSecretValue(theirPublicKey); }