package nebula import ( "crypto/ed25519" "crypto/rand" "encoding/json" "fmt" "github.com/slackhq/nebula/cert" ) // SigningPrivateKey wraps an ed25519.PrivateKey to provide convenient JSON // (un)marshaling methods. type SigningPrivateKey ed25519.PrivateKey // MarshalJSON implements the json.Marshaler interface. func (k SigningPrivateKey) MarshalJSON() ([]byte, error) { pemStr := cert.MarshalEd25519PrivateKey(ed25519.PrivateKey(k)) return json.Marshal(string(pemStr)) } // UnmarshalJSON implements the json.Unmarshaler interface. func (k *SigningPrivateKey) UnmarshalJSON(b []byte) error { var pemStr string if err := json.Unmarshal(b, &pemStr); err != nil { return fmt.Errorf("unmarshaling into string: %w", err) } key, _, err := cert.UnmarshalEd25519PrivateKey([]byte(pemStr)) if err != nil { return fmt.Errorf("unmarshaling from PEM: %w", err) } *k = SigningPrivateKey(key) return nil } // SigningPublicKey wraps an ed25519.PublicKey to provide convenient JSON // (un)marshaling methods. type SigningPublicKey ed25519.PublicKey // MarshalJSON implements the json.Marshaler interface. func (k SigningPublicKey) MarshalJSON() ([]byte, error) { pemStr := cert.MarshalEd25519PublicKey(ed25519.PublicKey(k)) return json.Marshal(string(pemStr)) } // MarshalJSON implements the json.Unmarshaler interface. func (k *SigningPublicKey) UnmarshalJSON(b []byte) error { var pemStr string if err := json.Unmarshal(b, &pemStr); err != nil { return fmt.Errorf("unmarshaling into string: %w", err) } key, _, err := cert.UnmarshalEd25519PublicKey([]byte(pemStr)) if err != nil { return fmt.Errorf("unmarshaling from PEM: %w", err) } *k = SigningPublicKey(key) return nil } // GenerateSigningPair generates and returns a new key pair which can be used // for signing arbitrary blobs of bytes. func GenerateSigningPair() (SigningPublicKey, SigningPrivateKey) { pub, priv, err := ed25519.GenerateKey(rand.Reader) if err != nil { panic(fmt.Errorf("generating ed25519 key: %w", err)) } return SigningPublicKey(pub), SigningPrivateKey(priv) }