Example #1
0
func handleConnection(c net.Conn, pub, priv *[32]byte) {
	defer c.Close()
	// first wait for the client's public key
	peerPubSlice := make([]byte, secure.KeySize)
	n, err := c.Read(peerPubSlice)

	if err != nil {
		log.Println(err)
		return
	}

	peerPubSlice = peerPubSlice[:n]
	var peerPub [secure.KeySize]byte
	copy(peerPub[:], peerPubSlice)

	// then, send our public key
	_, err = c.Write(pub[:])

	if err != nil {
		log.Println(err)
		return
	}

	// now session is "secure"
	sr := secure.NewReader(c, priv, &peerPub)
	sw := secure.NewWriter(c, priv, &peerPub)

	// echo
	_, err = io.Copy(sw, sr)

	if err != nil {
		log.Println(err)
	}
}
Example #2
0
// Dial generates a private/public key pair,
// connects to the server, perform the handshake
// and return a reader/writer.
func dial(addr string) (io.ReadWriteCloser, error) {
	pub, priv, err := box.GenerateKey(rand.Reader)

	if err != nil {
		return nil, err
	}

	conn, err := net.Dial("tcp", addr)

	if err != nil {
		return nil, err
	}

	// first thing we do is send our public key
	_, err = conn.Write(pub[:])

	if err != nil {
		return nil, err
	}

	// wait for the server's public key
	peerPubSlice := make([]byte, secure.KeySize)
	n, err := conn.Read(peerPubSlice)

	if err != nil {
		return nil, err
	}

	peerPubSlice = peerPubSlice[:n]
	var peerPub [secure.KeySize]byte
	copy(peerPub[:], peerPubSlice)

	secCon := secureConn{
		secure.NewReader(conn, priv, &peerPub),
		secure.NewWriter(conn, priv, &peerPub),
		conn,
	}

	return secCon, nil
}