-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
144 lines (118 loc) · 2.45 KB
/
client.go
File metadata and controls
144 lines (118 loc) · 2.45 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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
package main
import (
"bufio"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"fmt"
"io"
"net"
"os"
"strconv"
)
func main() {
ip := ipAddress()
port := portEntry()
port2 := strconv.Itoa(port)
ip2 := ip.String()
var listen string = ip2 + ":" + port2
connect(listen)
}
func ipAddress() net.IP {
var ipv4Addr net.IP
for {
var ipv4 string
fmt.Println("Enter the IP address of the server you want to connect: ")
fmt.Scanln(&ipv4)
ips, err := net.LookupIP(ipv4)
if err != nil {
fmt.Println("Invalid domain name or IP address. ")
}
yeni := ips[0].String()
ipv4Addr = net.ParseIP(yeni)
if ipv4Addr == nil {
fmt.Println("the IP address you entered is incorrect.")
continue
} else {
break
}
kontrol := ipv4Addr.DefaultMask()
if kontrol == nil {
fmt.Println("Invalid IP address. ")
} else {
break
}
}
return ipv4Addr
}
func portEntry() int {
var port string
var x int
var err error
for {
fmt.Println("Enter the port you want to connect: ")
fmt.Scanln(&port)
x, err = net.LookupPort("tcp", port)
if err != nil {
fmt.Println("Invalid port entry. ")
} else {
break
}
}
return x
}
func connect(listen string) {
conn, _ := net.Dial("tcp", listen)
if conn != nil {
fmt.Println("-----Launching server-----")
}
r := bufio.NewReader(conn)
publicKeyByte := make([]byte, 270)
_, err := io.ReadFull(r, publicKeyByte)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
publicKey, err := x509.ParsePKCS1PublicKey(publicKeyByte)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
clientPrivateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
fmt.Println(err.Error)
os.Exit(1)
}
clientPublicKey := &clientPrivateKey.PublicKey
sent := x509.MarshalPKCS1PublicKey(clientPublicKey)
conn.Write(sent)
for {
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)
r := bufio.NewReader(conn)
message := make([]byte, 256)
_, errr := io.ReadFull(r, message)
if errr != nil {
fmt.Println(err)
os.Exit(1)
}
plainText, err := rsa.DecryptPKCS1v15(rand.Reader, clientPrivateKey, []byte(message))
if err != nil {
fmt.Println(err)
os.Exit(1)
}
m := string(plainText[:])
fmt.Println("message received:", m)
}
}