~bigbes/core-go

ref: d0bf1153ada4f933f7db6a4856bfed4785cced14 core-go/crypto/crypto_test.go -rw-r--r-- 2.0 KiB
d0bf1153 — Adnan Maolood webhooks.FilterWebhooks: Filter by user_id 4 years 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
package crypto

import (
	"encoding/base64"
	"strings"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
	"github.com/vaughan0/go-ini"
)

func init() {
	config, err := ini.Load(strings.NewReader(`
[webhooks]
private-key=ebzsjPaN6E13ln/FeNWly1C92q6bVMVdOnDo1HPl5fc=

[sr.ht]
network-key=tbuG-7Vh44vrDq1L_HKWkHnWrDOtJhEkPKPiauaLeuk=`))
	if err != nil {
		panic(err)
	}
	InitCrypto(config)
}

func TestSignWebhook(t *testing.T) {
	payload := []byte("Hello world!")
	nonce, signature := SignWebhook(payload)

	sig, err := base64.StdEncoding.DecodeString(signature)
	assert.Nil(t, err)
	valid := Verify(append(payload, []byte(nonce)...), sig)
	assert.True(t, valid)
}

func TestVerifyWebhook(t *testing.T) {
	payload := []byte("Hello world!")
	nonce, signature := SignWebhook(payload)
	assert.True(t, VerifyWebhook(payload, nonce, signature))
}

func TestSign(t *testing.T) {
	payload := []byte("Hello world!")
	signature := Sign(payload)

	valid := Verify(payload, signature)
	assert.True(t, valid)

	valid = Verify([]byte("Something else"), signature)
	assert.False(t, valid)
}

func TestEncrypt(t *testing.T) {
	payload := []byte("Hello, world!")

	enc := Encrypt(payload)
	assert.NotNil(t, enc)
	assert.NotEqual(t, enc, []byte("Hello, world!"))

	dec := DecryptWithoutExpiration(enc)
	assert.NotNil(t, dec)
	assert.Equal(t, dec, []byte("Hello, world!"))
}

func TestEncryptWithExpire(t *testing.T) {
	payload := []byte("Hello, world!")

	enc := Encrypt(payload)
	assert.NotNil(t, enc)
	assert.NotEqual(t, enc, []byte("Hello, world!"))

	dec := DecryptWithExpiration(enc, 30*time.Minute)
	assert.NotNil(t, dec)
	assert.Equal(t, dec, []byte("Hello, world!"))

	time.Sleep(time.Duration(1))

	dec = DecryptWithExpiration(enc, time.Duration(2))
	assert.Nil(t, dec)
}

func TestBearerHMAC(t *testing.T) {
	payload := []byte("Hello, world!")
	mac := BearerHMAC(payload)

	valid := BearerVerify(payload, mac)
	assert.True(t, valid)

	valid = BearerVerify([]byte("Something else"), mac)
	assert.False(t, valid)
}