DEV Community

Cover image for Encrypted Stream for net.Conn or io.ReadWriter
Zheng "Bruce" Li for NKN

Posted on

Encrypted Stream for net.Conn or io.ReadWriter

It's surprising to find that no Golang library can easily transform a net.Conn to an encrypted and/or authenticated net.Conn. So I wrote one that works in one line, welcome to give it a try!

https://github.com/nknorg/encrypted-stream

Overview

Encrypted-stream is a Golang library that transforms any net.Conn or io.ReadWriter stream to an encrypted and/or authenticated stream.

The encrypted stream implements net.Conn and io.ReadWriter and can be used as drop-in replacement.

Works with any encryption, authentication, or authenticated encryption algorithm or even arbitrary transformation. Only a cipher that implements encrypt/decrypt needs to be provided. XSalsa20-Poly1305 and AES-GCM are provided as reference cipher.

The encrypted stream only adds a small constant memory overhead compared to the original stream.

Usage

Assume you have a net.Conn and you want to transform it into an encrypted net.Conn:

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

You first need to have a shared key at both side of the connection, (e.g. derived from key exchange algorithm, or pre-determined). Then all you need to do is to choose or implements a cipher:

encryptedConn, err := stream.NewEncryptedStream(conn, &stream.Config{
Cipher: stream.NewXSalsa20Poly1305Cipher(&key),
})

Now you can use encryptedConn just like conn, but everything is encrypted and authenticated.

See stream_test.go for complete example and benchmark with TCP connection.

Benchmark

$ go test -v -bench=. -run=^$
goos: darwin
goarch: amd64
pkg: github.com/nknorg/encrypted-stream
BenchmarkPipeXSalsa20Poly1305-12            4712        254008 ns/op     516.01 MB/s           1 B/op          0 allocs/op
BenchmarkPipeAESGCM128-12                  18675         65688 ns/op    1995.38 MB/s           0 B/op          0 allocs/op
BenchmarkPipeAESGCM256-12                  16060         74029 ns/op    1770.55 MB/s           0 B/op          0 allocs/op
BenchmarkTCPXSalsa20Poly1305-12             6760        263446 ns/op     497.53 MB/s           0 B/op          0 allocs/op
BenchmarkTCPAESGCM128-12                   14780         82979 ns/op    1579.57 MB/s           0 B/op          0 allocs/op
BenchmarkTCPAESGCM256-12                   13321         92393 ns/op    1418.64 MB/s           0 B/op          0 allocs/op
PASS
ok      github.com/nknorg/encrypted-stream  9.471s

Top comments (0)