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
|
package cryptoutil
import (
"bytes"
"encoding/hex"
"testing"
)
func mustHex(t *testing.T, s string) []byte {
t.Helper()
bytes, err := hex.DecodeString(s)
if err != nil {
t.Fatalf("Bad hex %q: %s", s, err)
}
return bytes
}
func TestPassword(t *testing.T) {
const password = "eclair scroll gliding sled shining removed ascend android cheer confetti"
hash, err := Hash(password)
if err != nil {
t.Fatalf("Hash(%q) failed: %s", password, err)
}
_, err = CheckPassword(password, hash)
if err != nil {
t.Errorf("CheckPassword(%q, %q) failed: %s", password, hash, err)
}
}
func TestSignature(t *testing.T) {
key := HMACKey(mustHex(t, "669e06ec457778b9a8133edb0a87ea82c6b141ffbbc63c038da96258175eb35c"))
msg := []byte("test message")
signedMsg := key.Sign(msg)
got, ok := key.Verify(signedMsg)
if !ok {
t.Fatalf("Verify(%x) rejected the message", signedMsg)
}
if !bytes.Equal(got, msg) {
t.Errorf("Verify(%x) = %x, want %x", signedMsg, got, msg)
}
}
func TestEncrypt(t *testing.T) {
key := EncryptionKey(mustHex(t, "b6de26860e0a39aa134732e58055c06ba028675453f73a6912bc932e58d5743d0e423217f06487d3e96a59980301fcc97dfcc4c6b19765f2947de3c33ab7ef9e"))
msg := []byte("test message")
encryptedMsg, err := key.Encrypt(msg)
if err != nil {
t.Fatalf("Encrypt(%q) failed: %s", msg, err)
}
got, err := key.Decrypt(encryptedMsg)
if err != nil {
t.Fatalf("Decrypt(%x) failed: %s", encryptedMsg, err)
}
if !bytes.Equal(got, msg) {
t.Errorf("Decrypt(%x) = %x, want %x", encryptedMsg, got, msg)
}
}
func TestDeriveKey(t *testing.T) {
const password = "automaker moisture botch tubular kelp rinse rule giggly donated stock"
hash, err := Hash(password)
if err != nil {
t.Fatalf("Hash(%q) failed: %s", password, err)
}
rawKey, err := CheckPassword(password, hash)
if err != nil {
t.Fatalf("CheckPassword(%q, %x) failed: %s", password, hash, err)
}
key, err := rawKey.EncryptionKey()
if err != nil {
t.Fatalf("EncryptionKey() failed: %s", err)
}
msg := []byte("test message")
encryptedMsg, err := key.Encrypt(msg)
if err != nil {
t.Fatalf("Encrypt(%q) failed: %s", msg, err)
}
got, err := key.Decrypt(encryptedMsg)
if err != nil {
t.Fatalf("Decrypt(%x) failed: %s", encryptedMsg, err)
}
if !bytes.Equal(got, msg) {
t.Errorf("Decrypt(%x) = %x, want %x", encryptedMsg, got, msg)
}
}
|