/
56.go
49 lines (44 loc) · 1.18 KB
/
56.go
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
package main
import (
"bytes"
"crypto/rand"
"crypto/rsa"
"crypto/sha1"
"encoding/gob"
. "fmt"
. "net"
)
var HELLO_WORLD = []byte("Hello World")
var RSA_LABEL = []byte("served")
func main() {
Serve(":1025", func(connection *UDPConn, c *UDPAddr, packet *bytes.Buffer) (n int) {
var key rsa.PublicKey
if e := gob.NewDecoder(packet).Decode(&key); e == nil {
if response, e := rsa.EncryptOAEP(sha1.New(), rand.Reader, &key, HELLO_WORLD, RSA_LABEL); e == nil {
n, _ = connection.WriteToUDP(response, c)
}
}
return
})
}
func Serve(address string, f func(*UDPConn, *UDPAddr, *bytes.Buffer) int) {
Launch(address, func(connection *UDPConn) {
for {
buffer := make([]byte, 1024)
if n, client, e := connection.ReadFromUDP(buffer); e == nil {
go func(c *UDPAddr, b []byte) {
if n := f(connection, c, bytes.NewBuffer(b)); n != 0 {
Println(n, "bytes written to", c)
}
}(client, buffer[:n])
}
}
})
}
func Launch(address string, f func(*UDPConn)) {
if a, e := ResolveUDPAddr("udp", address); e == nil {
if server, e := ListenUDP("udp", a); e == nil {
f(server)
}
}
}