services/crypto.go keeps its function names and its KEY_ENCRYPTION_KEY lookup and delegates the cipher, so vantagectl's verify probe can decrypt with the same implementation rather than a second copy.
80 lines
1.7 KiB
Go
80 lines
1.7 KiB
Go
package cryptobox
|
|
|
|
import (
|
|
"bytes"
|
|
"crypto/rand"
|
|
"encoding/hex"
|
|
"testing"
|
|
)
|
|
|
|
func testKey(t *testing.T) []byte {
|
|
t.Helper()
|
|
k := make([]byte, KeySize)
|
|
if _, err := rand.Read(k); err != nil {
|
|
t.Fatalf("rand: %v", err)
|
|
}
|
|
return k
|
|
}
|
|
|
|
func TestSealOpenRoundTrip(t *testing.T) {
|
|
key := testKey(t)
|
|
sealed, err := Seal(key, "hunter2")
|
|
if err != nil {
|
|
t.Fatalf("Seal: %v", err)
|
|
}
|
|
if _, err := hex.DecodeString(sealed); err != nil {
|
|
t.Fatalf("Seal output is not hex: %v", err)
|
|
}
|
|
if bytes.Contains([]byte(sealed), []byte("hunter2")) {
|
|
t.Fatal("plaintext appears in ciphertext")
|
|
}
|
|
got, err := Open(key, sealed)
|
|
if err != nil {
|
|
t.Fatalf("Open: %v", err)
|
|
}
|
|
if got != "hunter2" {
|
|
t.Fatalf("got %q, want %q", got, "hunter2")
|
|
}
|
|
}
|
|
|
|
func TestSealIsNonDeterministic(t *testing.T) {
|
|
key := testKey(t)
|
|
a, err := Seal(key, "same")
|
|
if err != nil {
|
|
t.Fatalf("Seal: %v", err)
|
|
}
|
|
b, err := Seal(key, "same")
|
|
if err != nil {
|
|
t.Fatalf("Seal: %v", err)
|
|
}
|
|
if a == b {
|
|
t.Fatal("two seals of the same plaintext are identical; nonce is not random")
|
|
}
|
|
}
|
|
|
|
func TestOpenWrongKeyFails(t *testing.T) {
|
|
sealed, err := Seal(testKey(t), "secret")
|
|
if err != nil {
|
|
t.Fatalf("Seal: %v", err)
|
|
}
|
|
if _, err := Open(testKey(t), sealed); err == nil {
|
|
t.Fatal("Open with the wrong key succeeded")
|
|
}
|
|
}
|
|
|
|
func TestOpenRejectsBadInput(t *testing.T) {
|
|
key := testKey(t)
|
|
if _, err := Open(key, "not-hex"); err == nil {
|
|
t.Fatal("Open accepted non-hex input")
|
|
}
|
|
if _, err := Open(key, "abcd"); err == nil {
|
|
t.Fatal("Open accepted a ciphertext shorter than the nonce")
|
|
}
|
|
}
|
|
|
|
func TestWrongKeySizeRejected(t *testing.T) {
|
|
if _, err := Seal(make([]byte, 16), "x"); err == nil {
|
|
t.Fatal("Seal accepted a 16-byte key")
|
|
}
|
|
}
|