-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
108 lines (90 loc) · 1.83 KB
/
server.go
File metadata and controls
108 lines (90 loc) · 1.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package main
import (
"bufio"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"fmt"
"io"
"net"
"os"
"strconv"
)
func main() {
port := portEntry()
port2 := strconv.Itoa(port)
port2 = ":" + port2
listenPort(port2)
}
func portEntry() int {
var port string
var x int
var err error
for {
fmt.Println("enter the port you want to open the connection to: ")
fmt.Scanln(&port)
x, err = net.LookupPort("tcp", port)
if err != nil {
fmt.Println("Invalid port entry. ")
} else {
break
}
}
return x
}
func listenPort(t string) {
ln, _ := net.Listen("tcp", t)
conn, _ := ln.Accept()
if conn != nil {
fmt.Println("-----Launching client-----")
}
serverPrivateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
fmt.Println(err.Error)
os.Exit(1)
}
serverPublicKey := &serverPrivateKey.PublicKey
sent := x509.MarshalPKCS1PublicKey(serverPublicKey)
conn.Write(sent)
a := bufio.NewReader(conn)
publicKeyByte := make([]byte, 270)
_, er := io.ReadFull(a, publicKeyByte)
publicKey, err := x509.ParsePKCS1PublicKey(publicKeyByte)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
if er != nil {
fmt.Println(err)
os.Exit(1)
}
for {
r := bufio.NewReader(conn)
message := make([]byte, 256)
_, err := io.ReadFull(r, message)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
plainText, err := rsa.DecryptPKCS1v15(rand.Reader, serverPrivateKey, []byte(message))
if err != nil {
fmt.Println(err)
os.Exit(1)
}
m := string(plainText[:])
fmt.Println("message received:", m)
reader := bufio.NewReader(os.Stdin)
fmt.Print("Text to send: ")
text, err := reader.ReadBytes('\n')
if err != nil {
fmt.Println(err)
os.Exit(1)
}
ciphertext, err := rsa.EncryptPKCS1v15(rand.Reader, publicKey, text)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
conn.Write(ciphertext)
}
}