keys.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package keys
  2. import (
  3. "errors"
  4. "fmt"
  5. "sync"
  6. "github.com/DataDog/go-tuf/data"
  7. )
  8. // SignerMap stores mapping between key type strings and signer constructors.
  9. var SignerMap sync.Map
  10. // Verifier stores mapping between key type strings and verifier constructors.
  11. var VerifierMap sync.Map
  12. var (
  13. ErrInvalid = errors.New("tuf: signature verification failed")
  14. ErrInvalidKey = errors.New("invalid key")
  15. )
  16. // A Verifier verifies public key signatures.
  17. type Verifier interface {
  18. // UnmarshalPublicKey takes key data to a working verifier implementation for the key type.
  19. // This performs any validation over the data.PublicKey to ensure that the verifier is usable
  20. // to verify signatures.
  21. UnmarshalPublicKey(key *data.PublicKey) error
  22. // MarshalPublicKey returns the data.PublicKey object associated with the verifier.
  23. MarshalPublicKey() *data.PublicKey
  24. // This is the public string used as a unique identifier for the verifier instance.
  25. Public() string
  26. // Verify takes a message and signature, all as byte slices,
  27. // and determines whether the signature is valid for the given
  28. // key and message.
  29. Verify(msg, sig []byte) error
  30. }
  31. type Signer interface {
  32. // MarshalPrivateKey returns the private key data.
  33. MarshalPrivateKey() (*data.PrivateKey, error)
  34. // UnmarshalPrivateKey takes private key data to a working Signer implementation for the key type.
  35. UnmarshalPrivateKey(key *data.PrivateKey) error
  36. // Returns the public data.PublicKey from the private key
  37. PublicData() *data.PublicKey
  38. // Sign returns the signature of the message.
  39. // The signer is expected to do its own hashing, so the full message will be
  40. // provided as the message to Sign with a zero opts.HashFunc().
  41. SignMessage(message []byte) ([]byte, error)
  42. }
  43. func GetVerifier(key *data.PublicKey) (Verifier, error) {
  44. st, ok := VerifierMap.Load(key.Type)
  45. if !ok {
  46. return nil, ErrInvalidKey
  47. }
  48. s := st.(func() Verifier)()
  49. if err := s.UnmarshalPublicKey(key); err != nil {
  50. return nil, fmt.Errorf("tuf: error unmarshalling key: %w", err)
  51. }
  52. return s, nil
  53. }
  54. func GetSigner(key *data.PrivateKey) (Signer, error) {
  55. st, ok := SignerMap.Load(key.Type)
  56. if !ok {
  57. return nil, ErrInvalidKey
  58. }
  59. s := st.(func() Signer)()
  60. if err := s.UnmarshalPrivateKey(key); err != nil {
  61. return nil, fmt.Errorf("tuf: error unmarshalling key: %w", err)
  62. }
  63. return s, nil
  64. }