更新:感谢peterSO,错误似乎是随机字节,读取为字符串将包含“\ n”,这会导致换行和错误。问题既不是
io.Copy(conn, bytes.NewReader(encrypted))
也不
conn.Write([]byte(encrypted))
工作。任何人都知道如何将chipertext写入conn?
原帖: 聊天程序由一台服务器和两个客户端组成。它使用 TLS 和 NaCl 进行(端到端)加密。在 3/4 的情况下它可以工作,但有时我会收到一个错误:
panic: runtime error: slice bounds out of range
goroutine 34 [running]:
main.handleConnection(0x600a60, 0xc04246c000)
path-to/client.go:79
+0x3a6
created by main.main
path-to/client.go:44
+0x436
exit status 2
44号线电话
go handleConnection(conn)
第 79 行是“解密”行:
func handleConnection(conn net.Conn) {
defer conn.Close()
input := bufio.NewScanner(conn)
for input.Scan() {
senderPublicKey := readKey("localPublic")
recipientPrivateKey := readKey("remotePrivate")
var decryptNonce [24]byte
encrypted := input.Bytes()
copy(decryptNonce[:], encrypted[:24])
decrypted, ok := box.Open(nil, encrypted[24:], &decryptNonce, senderPublicKey, recipientPrivateKey)
if !ok {
fmt.Println("decryption error")
}
fmt.Println(BytesToString(decrypted))
}
}
完整的代码在下面。由于它在没有加密的情况下完美地工作并且仅加密的测试实现也可以工作,我会指出客户端 - 服务器 - 客户端之间的传输。通常切片的长度不应该改变,因为输出应该保持不变?
客户阅读:
package main
import (
"bufio"
crypto_rand "crypto/rand"
"crypto/tls"
"crypto/x509"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"os"
"golang.org/x/crypto/nacl/box"
)
func main() {
cert, err := tls.LoadX509KeyPair("cert.pem", "key.pem")
if err != nil {
log.Fatalln("Unable to load cert", err)
}
clientCACert, err := ioutil.ReadFile("cert.pem")
if err != nil {
log.Fatal("Unable to open cert", err)
}
clientCertPool := x509.NewCertPool()
clientCertPool.AppendCertsFromPEM(clientCACert)
conf := &tls.Config{
Certificates: []tls.Certificate{cert},
RootCAs: clientCertPool,
//InsecureSkipVerify: true,
}
conn, err := tls.Dial("tcp", "localhost:443", conf)
if err != nil {
log.Fatal(err)
}
defer conn.Close()
go handleConnection(conn)
for {
stdin := bufio.NewReader(os.Stdin)
textIn, err := stdin.ReadBytes('\n')
if err != nil {
fmt.Println(err)
}
var nonce [24]byte
if _, err := io.ReadFull(crypto_rand.Reader, nonce[:]); err != nil {
panic(err)
}
senderPrivateKey := readKey("localPrivate")
recipientPublicKey := readKey("remotePublic")
encrypted := box.Seal(nonce[:], textIn, &nonce, recipientPublicKey, senderPrivateKey)
text := BytesToString(encrypted)
fmt.Fprintf(conn, text+"\n")
}
}
func handleConnection(conn net.Conn) {
defer conn.Close()
input := bufio.NewScanner(conn)
for input.Scan() {
senderPublicKey := readKey("localPublic")
recipientPrivateKey := readKey("remotePrivate")
var decryptNonce [24]byte
encrypted := input.Bytes()
copy(decryptNonce[:], encrypted[:24])
decrypted, ok := box.Open(nil, encrypted[24:], &decryptNonce, senderPublicKey, recipientPrivateKey)
if !ok {
fmt.Println("decryption error")
}
fmt.Println(BytesToString(decrypted))
}
}
//BytesToString converts []byte to str
func BytesToString(data []byte) string {
return string(data[:])
}
//Read the keys from file, pass filename without .ending
func readKey(name string) (prv *[32]byte) {
prv = new([32]byte)
f, err := os.Open(name + ".key")
if err != nil {
panic(err)
}
_, err = io.ReadFull(f, prv[:])
if err != nil {
panic(err)
}
return
}
服务器端:
package main
import (
"bufio"
"crypto/tls"
"fmt"
"log"
"net"
)
type client chan<- string // an outgoing message channel
var (
entering = make(chan client)
leaving = make(chan client)
messages = make(chan string) // all incoming client messages
)
// Broadcast incoming message to all clients' outgoing message channels.
func broadcaster() {
clients := make(map[client]bool) // all connected clients
for {
select {
case msg := <-messages:
for cli := range clients {
cli <- msg
}
case cli := <-entering:
clients[cli] = true
case cli := <-leaving:
delete(clients, cli)
close(cli)
}
}
}
func handleConn(conn net.Conn) {
ch := make(chan string) // outgoing client messages
go clientWriter(conn, ch)
//who := conn.RemoteAddr().String()
entering <- ch
//messages <- who + " has arrived"
input := bufio.NewScanner(conn)
for input.Scan() {
messages <- input.Text()
}
//messages <- who + " has left"
leaving <- ch
conn.Close()
}
func clientWriter(conn net.Conn, ch <-chan string) {
for msg := range ch {
fmt.Fprintln(conn, msg)
}
}
func main() {
cer, err := tls.LoadX509KeyPair("cert.pem", "key.pem")
if err != nil {
log.Println(err)
return
}
config := &tls.Config{
Certificates: []tls.Certificate{cer},
//PFS, this will reject client with RSA certificates
CipherSuites: []uint16{tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384},
//Force it server side
PreferServerCipherSuites: true,
//Force TLS Version
MinVersion: tls.VersionTLS12}
listener, err := tls.Listen("tcp", "localhost:443", config)
if err != nil {
log.Fatal(err)
}
go broadcaster()
for {
conn, err := listener.Accept()
if err != nil {
log.Print(err)
continue
}
go handleConn(conn)
}
}