summaryrefslogtreecommitdiffstats
path: root/internal/cryptoutil/cryptoutil_test.go
diff options
context:
space:
mode:
Diffstat (limited to 'internal/cryptoutil/cryptoutil_test.go')
-rw-r--r--internal/cryptoutil/cryptoutil_test.go85
1 files changed, 85 insertions, 0 deletions
diff --git a/internal/cryptoutil/cryptoutil_test.go b/internal/cryptoutil/cryptoutil_test.go
new file mode 100644
index 0000000..6235878
--- /dev/null
+++ b/internal/cryptoutil/cryptoutil_test.go
@@ -0,0 +1,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)
+ }
+}