From 735283360637e8c66f3de4d549855ba99f14a193 Mon Sep 17 00:00:00 2001 From: Quint Daenen Date: Mon, 6 May 2024 18:48:23 +0200 Subject: [PATCH] Add principal utility funcs. --- principal/principal.go | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/principal/principal.go b/principal/principal.go index a44f080..63b9988 100644 --- a/principal/principal.go +++ b/principal/principal.go @@ -1,6 +1,8 @@ package principal import ( + "bytes" + "crypto/rand" "crypto/sha256" "encoding/base32" "encoding/binary" @@ -20,6 +22,30 @@ type Principal struct { Raw []byte } +// NewRandomPrincipal returns a new random principal. +func NewRandomPrincipal() Principal { + var raw [29]byte + _, err := rand.Read(raw[:]) + if err != nil { + panic(err) + } + return Principal{Raw: raw[:]} +} + +// Equal checks if two principals are equal. +func (p Principal) Equal(other Principal) bool { + return bytes.Equal(p.Raw, other.Raw) +} + +// MustDecode converts a textual representation into a principal. It panics if the input is invalid. +func MustDecode(s string) Principal { + p, err := Decode(s) + if err != nil { + panic(err) + } + return p +} + // Decode converts a textual representation into a principal. func Decode(s string) (Principal, error) { p := strings.Split(s, "-")