Skip to content

Instantly share code, notes, and snippets.

@matejstrnad
Created Oct 19, 2020
Embed
What would you like to do?
package main
import (
"bufio"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"fmt"
"net"
"os"
)
func PkToString(k rsa.PublicKey) string {
return string(
pem.EncodeToMemory(
&pem.Block{
Type: "RSA PUBLIC KEY",
Bytes: x509.MarshalPKCS1PublicKey(&k),
},
),
)
}
func read(c net.Conn) string {
m, err := bufio.NewReader(c).ReadString('\n')
if err != nil {
fmt.Println(err)
}
return m
}
func getSecurityCode(publicKey rsa.PublicKey) string {
hash := sha256.Sum256([]byte(string(publicKey.E) + publicKey.N.String()))
return string(hash[:4]) + string(hash[4:])
}
// https://stackoverflow.com/questions/15334220/encode-decode-base64
func EncodeB64(message string) string {
base64Text := make([]byte, base64.StdEncoding.EncodedLen(len(message)))
base64.StdEncoding.Encode(base64Text, []byte(message))
return string(base64Text)
}
func DecodeB64(message string) string {
base64Text := make([]byte, base64.StdEncoding.DecodedLen(len(message)))
base64.StdEncoding.Decode(base64Text, []byte(message))
fmt.Printf("base64: %s\n", base64Text)
return string(base64Text)
}
func initConn(c net.Conn, privateKey *rsa.PrivateKey, publicKey rsa.PublicKey, masterKey *[]byte) bool {
reader := bufio.NewReader(os.Stdin)
c.Write([]byte("hi server\n"))
if read(c) != "hi client" {
//return false
}
cID := read(c)
c.Write([]byte("pk\n"))
if read(c) != "ok" {
//return false
}
c.Write([]byte(EncodeB64(PkToString(publicKey)) + "\n"))
if read(c) != "ok" {
//return false
}
fmt.Println("Create conversation? (y/n)")
text1, _ := reader.ReadString('\n')
if text1 == "y" {
fmt.Println("Conversation id: " + cID)
c.Write([]byte("wu\n"))
if read(c) != "uc" {
return false
}
fmt.Println("Receiver connected")
} else {
if read(c) != "to" {
return false
}
fmt.Println("Conversation id: ")
text2, _ := reader.ReadString('\n')
c.Write([]byte(text2 + "\n"))
}
tpkH, err := x509.ParsePKCS1PublicKey([]byte(DecodeB64(read(c))))
tpk := *tpkH
if err != nil {
return false
}
fmt.Println("Your security code: " + getSecurityCode(publicKey))
fmt.Println("Receiver security code: " + getSecurityCode(tpk))
fmt.Println("Please verify your security codes.")
return true
}
const IP = "127.0.0.1"
func main() {
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
masterKey := make([]byte, 64)
if err != nil {
fmt.Println(err)
return
}
publicKey := privateKey.PublicKey
c, err := net.Dial("tcp4", IP+":8221")
initConn(c, privateKey, publicKey, &masterKey)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment