Code example for X509EncodedKeySpec

        writeUTF(new String(Base64.encodeBase64(key.getEncoded())));
    public X509EncodedKeySpec readKey() throws IOException {
        byte[] otherHalf = Base64.decodeBase64(readUTF());
        return new X509EncodedKeySpec(otherHalf);
     * Performs a Diffie-Hellman key exchange and produce a common secret between two ends of the connection. 
     * <p> 
     * DH is also useful as a coin-toss algorithm. Two parties get the same random number without trusting 
     * each other. 
    public KeyAgreement diffieHellman(boolean side) throws IOException, GeneralSecurityException {
        KeyPair keyPair;
        PublicKey otherHalf;
        if (side) {
            AlgorithmParameterGenerator paramGen = AlgorithmParameterGenerator.getInstance("DH");
            KeyPairGenerator dh = KeyPairGenerator.getInstance("DH");
            keyPair = dh.generateKeyPair();
            // send a half and get a half 
            otherHalf = KeyFactory.getInstance("DH").generatePublic(readKey());
        } else { 
            otherHalf = KeyFactory.getInstance("DH").generatePublic(readKey());
            KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("DH");
            keyPairGen.initialize(((DHPublicKey) otherHalf).getParams());
Connect your IDE to all the code out there  Get Codota for Java