39 lines
954 B
Go
39 lines
954 B
Go
package device
|
|
|
|
import (
|
|
"crypto/ed25519"
|
|
"encoding/base64"
|
|
"testing"
|
|
)
|
|
|
|
func TestLoadOrCreatePersist(t *testing.T) {
|
|
dir := t.TempDir()
|
|
id1, err := LoadOrCreate(dir, "test-device")
|
|
if err != nil {
|
|
t.Fatalf("create: %v", err)
|
|
}
|
|
// 再次加载应得到同一公钥
|
|
id2, err := LoadOrCreate(dir, "test-device")
|
|
if err != nil {
|
|
t.Fatalf("reload: %v", err)
|
|
}
|
|
if id1.PublicKey != id2.PublicKey {
|
|
t.Fatal("public key should persist across reloads")
|
|
}
|
|
}
|
|
|
|
func TestSignVerify(t *testing.T) {
|
|
dir := t.TempDir()
|
|
id, _ := LoadOrCreate(dir, "d")
|
|
payload := []byte("nonce-1|123456")
|
|
sigB64 := id.Sign(payload)
|
|
sig, _ := base64.StdEncoding.DecodeString(sigB64)
|
|
pub, _ := base64.StdEncoding.DecodeString(id.PublicKey)
|
|
if !ed25519.Verify(ed25519.PublicKey(pub), payload, sig) {
|
|
t.Fatal("signature should verify")
|
|
}
|
|
if ed25519.Verify(ed25519.PublicKey(pub), []byte("tampered"), sig) {
|
|
t.Fatal("tampered payload should fail verify")
|
|
}
|
|
}
|