Skip to content

Instantly share code, notes, and snippets.

@cyantarek
Created October 5, 2018 16:42
Show Gist options
  • Save cyantarek/639e52f06e0d2be8b5b14d946625b359 to your computer and use it in GitHub Desktop.
Save cyantarek/639e52f06e0d2be8b5b14d946625b359 to your computer and use it in GitHub Desktop.
Golang AES-CFB encrypted TCP stream
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"fmt"
"io"
"net"
)
func main() {
key := []byte("example key 1234")
conn, err := net.Dial("tcp", "127.0.0.1:9080")
if err != nil {
panic(err)
}
defer func() {
fmt.Println("Bye")
conn.Close()
}()
block, cipherErr := aes.NewCipher(key)
if cipherErr != nil {
fmt.Errorf("Can't create cipher:", cipherErr)
return
}
iv := make([]byte, aes.BlockSize)
if _, randReadErr := io.ReadFull(rand.Reader, iv); randReadErr != nil {
fmt.Errorf("Can't build random iv", randReadErr)
return
}
_, ivWriteErr := conn.Write(iv)
if ivWriteErr != nil {
fmt.Errorf("Can't send IV:", ivWriteErr)
return
} else {
fmt.Println("IV Sent:", iv)
}
stream := cipher.NewCFBEncrypter(block, iv)
data := [][]byte{
[]byte("Test one"),
[]byte("Hello crypto"),
[]byte("Hello word"),
[]byte("Hello excel"),
[]byte("Hello powerpoint"),
}
for _, d := range data {
encrypted := make([]byte, len(d))
stream.XORKeyStream(encrypted, d)
writeLen, writeErr := conn.Write(encrypted)
if writeErr != nil {
fmt.Errorf("Write failed:", writeErr)
return
}
fmt.Println("Encrypted Data Written:", string(d), encrypted, writeLen)
}
}
package main
import (
"crypto/aes"
"crypto/cipher"
"fmt"
"io"
"net"
)
func main() {
ln, err := net.Listen("tcp", "127.0.0.1:9080")
if err != nil {
panic(err)
}
key := []byte("example key 1234")
fmt.Println("Started Listening")
if err != nil {
panic(err)
}
for {
conn, err := ln.Accept()
if err != nil {
fmt.Errorf(
"Error while handling request from",
conn.RemoteAddr(),
":",
err,
)
}
go func(conn net.Conn) {
defer func() {
fmt.Println(
conn.RemoteAddr(),
"Closed",
)
conn.Close()
}()
block, blockErr := aes.NewCipher(key)
if blockErr != nil {
fmt.Println("Error creating cipher:", blockErr)
return
}
iv := make([]byte, 16)
ivReadLen, ivReadErr := conn.Read(iv)
if ivReadErr != nil {
fmt.Println("Can't read IV:", ivReadErr)
return
}
iv = iv[:ivReadLen]
if len(iv) < aes.BlockSize {
fmt.Println("Invalid IV length:", len(iv))
return
}
fmt.Println("Received IV:", iv)
stream := cipher.NewCFBDecrypter(block, iv)
fmt.Println("Hello", conn.RemoteAddr())
buf := make([]byte, 4096)
for {
rLen, rErr := conn.Read(buf)
if rErr == nil {
stream.XORKeyStream(buf[:rLen], buf[:rLen])
fmt.Println("Data:", string(buf[:rLen]), rLen)
continue
}
if rErr == io.EOF {
stream.XORKeyStream(buf[:rLen], buf[:rLen])
fmt.Println("Data:", string(buf[:rLen]), rLen, "EOF -")
break
}
fmt.Errorf(
"Error while reading from",
conn.RemoteAddr(),
":",
rErr,
)
break
}
}(conn)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment