示例#1
0
func TestEncryptAndDecryptData(t *testing.T) {
	key := make([]byte, 32)
	copy(key, []byte("this is my key!"))
	plaintext := "yay for me"
	addata := make([]byte, 10)
	copy(addata, []byte("ok"))

	//Test key length.Key must be 32 bytes.
	if _, err := server.EncryptData(key[1:], []byte(plaintext), addata); err == nil {
		t.Errorf("EncryptData error: %s", "key is not 32 length, this should be error, but not!")
	}

	//Test EncryptData main function.
	ciphertext, err := server.EncryptData(key, []byte(plaintext), addata)
	if err != nil {
		t.Errorf("EncryptData error: %v", err)
	} else {
		t.Logf("ciphertext is %x", ciphertext)
	}

	//Check decrypt
	p, err := server.DecryptData(key, ciphertext, addata)
	//c, err := chacha20poly1305.New(key)

	//p, err := c.Open(nil, ciphertext[len(ciphertext)-c.NonceSize():], ciphertext[:len(ciphertext)-c.NonceSize()], addata)
	if err != nil {
		t.Errorf("Decrypt data fail: %v", err)
	} else {
		t.Logf("plantext is %s", p)
	}

}
示例#2
0
func TestUdpServe(t *testing.T) {
	key := make([]byte, 32)
	copy(key, "this is my key value!")

	udpaddr, err := net.ResolveUDPAddr("udp", "localhost:8080")
	if err != nil {
		t.Fatalf("ResolveUDPAddr error : %v\n", err)
	}

	udpconn, err := net.DialUDP("udp", nil, udpaddr)
	if err != nil {
		t.Fatalf("DialUDP error : %v\n", err)
	}
	defer udpconn.Close()
	udpconn.SetDeadline(time.Now().Add(time.Duration(10) * time.Second))

	plaintext := []byte("a")
	ciphertext, err := server.EncryptData(key, plaintext, nil)
	if err != nil {
		t.Fatalf("EncryptData error : %v\n", err)
	}

	_, err = udpconn.Write(ciphertext)
	if err != nil {
		t.Fatalf("Write error : %v\n", err)
	}
}
示例#3
0
func TestTcpServe(t *testing.T) {
	key := make([]byte, 32)
	copy(key, "this is my key value!")
	//go server.TcpServe("localhost:8080", key)

	tcpaddr, err := net.ResolveTCPAddr("tcp", "localhost:8080")
	if err != nil {
		t.Fatalf("ResolveTCPAddr error : %v\n", err)
	}
	tcpconn, err := net.DialTCP("tcp", nil, tcpaddr)
	if err != nil {
		t.Fatalf("DialTCP error : %v\n", err)
	}
	defer tcpconn.Close()
	//tcpconn.SetDeadline(time.Now().Add(time.Duration(10) * time.Second))
	plaintext := []byte("this is plaintext")
	ciphertext, err := server.EncryptData(key, plaintext, nil)
	if err != nil {
		t.Fatalf("EncryptData error : %v\n", err)
	}

	bufWriter := bufio.NewWriter(tcpconn)
	t.Logf("ciphertext is %x\n", ciphertext)
	marshall := netstring.Marshall(ciphertext)
	t.Logf("marshall data is %x, len is %d\n", marshall, len(marshall))
	_, err = bufWriter.Write(marshall)
	if err != nil {
		t.Fatalf("Write error : %v\n", err)
	}
	bufWriter.Flush()
	tcpconn.CloseWrite()

	rdata := make([]byte, 50)
	rlen, err := tcpconn.Read(rdata)
	if err != nil {
		t.Fatalf("Read error : %v\n", err)
	} else {
		t.Logf("return data is %s\n", rdata[:rlen])

	}
}