func TestSecureWriter(t *testing.T) { priv, pub := &[32]byte{'p', 'r', 'i', 'v'}, &[32]byte{'p', 'u', 'b'} r, w := io.Pipe() secureW := secureio.NewSecureWriter(w, priv, pub) // Make sure we are secure // Encrypt hello world go func() { fmt.Fprintf(secureW, "hello world\n") w.Close() }() // Read from the underlying transport instead of the decoder buf, err := ioutil.ReadAll(r) if err != nil { t.Fatal(err) } // Make sure we dont' read the plain text message. if res := string(buf); res == "hello world\n" { t.Fatal("Unexpected result. The message is not encrypted.") } r, w = io.Pipe() secureW = secureio.NewSecureWriter(w, priv, pub) // Make sure we are unique // Encrypt hello world go func() { fmt.Fprintf(secureW, "hello world\n") w.Close() }() // Read from the underlying transport instead of the decoder buf2, err := ioutil.ReadAll(r) if err != nil { t.Fatal(err) } // Make sure we dont' read the plain text message. if string(buf) == string(buf2) { t.Fatal("Unexpected result. The encrypted message is not unique.") } }
// echo performs a public-key handshake with a provided network connection and // uses a secure reader and writer to unencrypt and re-encrypt any message sent // on the connection, echoing the message back. func echo(c net.Conn, priv, pub *[32]byte, errc chan error) { peersPub, err := receivePublic(c) if err != nil { c.Write([]byte("error receiving public key")) return } if err := sendPublic(c, pub); err != nil { errc <- err } secureR := secureio.NewSecureReader(c, priv, peersPub) secureW := secureio.NewSecureWriter(c, priv, peersPub) io.Copy(secureW, secureR) }
func TestReadWriterPing(t *testing.T) { priv, pub := &[32]byte{'p', 'r', 'i', 'v'}, &[32]byte{'p', 'u', 'b'} r, w := io.Pipe() defer w.Close() secureR := secureio.NewSecureReader(r, priv, pub) secureW := secureio.NewSecureWriter(w, priv, pub) // Encrypt hello world go fmt.Fprintf(secureW, "hello world\n") // Decrypt message buf := make([]byte, 1024) n, err := secureR.Read(buf) if err != nil { t.Fatal(err) } buf = buf[:n] // Make sure we have hello world back if res := string(buf); res != "hello world\n" { t.Fatalf("Unexpected result: %s != %s", res, "hello world") } }