~bfiedler/go-threema

ref: 293b4955ddb3d6787cdf34c6cb77e7525da0d912 go-threema/client/crypto_test.go -rw-r--r-- 2.3 KiB
293b4955 — Ben Fiedler Use hex.EncodeToString where appropriate 1 year, 8 months ago
                                                                                
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
package client

import (
	"testing"

	"github.com/stretchr/testify/assert"
	"golang.org/x/crypto/nacl/box"
)

var (
	c *client
)

func init() {
	var err error
	c, err = newClient("*DUMMYID", "apisecret")
	if err != nil {
		panic(err)
	}
}

func TestComputePublicKey(t *testing.T) {
	got := computePublicKey(privateKey)
	assert.Equal(t, publicKey, got)
}

// Test case available on the Threema Gateway documentation
// https://gateway.threema.ch/en/developer/api
func TestHashPhone(t *testing.T) {
	t.Parallel()

	phone := "41791234567"
	hash, err := c.hashPhone(phone)
	assert.Nil(t, err)
	assert.Equal(t, "ad398f4d7ebe63c6550a486cc6e07f9baa09bd9d8b3d8cb9d9be106d35a7fdbc", hash)
}

// Test case available on the Threema Gateway documentation
// https://gateway.threema.ch/en/developer/api
func TestHashEmail(t *testing.T) {
	t.Parallel()

	tests := map[string]string{
		"Normal":                 "test@threema.ch",
		"SpacePadding":           "  test@threema.ch    ",
		"Capitalization":         "tEST@THReeMa.cH",
		"Padding+Capitalization": "  TEst@tHReeMA.Ch  ",
	}

	for name, testcase := range tests {
		t.Run(name, func(t *testing.T) {
			hash, err := c.hashEmail(testcase)
			assert.Nil(t, err)
			assert.Equal(t, "1ea093239cc5f0e1b6ec81b866265b921f26dc4033025410063309f4d1a8ee2c", hash)
		})
	}
}

// Test case available on the Threema Gateway documentation
// https://gateway.threema.ch/en/developer/api
func TestNewTextMessage(t *testing.T) {
	msg := "hello threema"
	out, err := newTextMessage(msg)
	assert.Nil(t, err)

	assert.Equal(t, TextMessage, out[0], "wrong message type byte")
	assert.Equal(t, out[1:14], []byte(msg))
	assertPadding(t, out[14:])
}

func TestEncryptMessage(t *testing.T) {
	b, n, err := e2eClient.encryptTextMessage(publicKey, "test message")
	assert.Nil(t, err)

	msg, ok := box.Open(nil, b, &n, &publicKey, &privateKey)
	assert.True(t, ok)
	assert.Equal(t, TextMessage, msg[0], "wrong message type byte")
	assert.Equal(t, msg[1:13], []byte("test message"))
	assertPadding(t, msg[13:])
}

func assertPadding(t *testing.T, slice []byte) {
	padding := slice[0]
	if padding <= 0 || padding > 255 {
		t.Errorf("invalid padding. expected 1 <= padding <= 255, got: %v", padding)
	}

	for _, val := range slice {
		if padding != val {
			t.Errorf("invalid padding. expected: %v, got: %v", padding, val)
		}
	}
}