ecdsa.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package keys
  2. import (
  3. "crypto/ecdsa"
  4. "crypto/elliptic"
  5. "crypto/sha256"
  6. "encoding/asn1"
  7. "encoding/json"
  8. "errors"
  9. "math/big"
  10. "github.com/DataDog/go-tuf/data"
  11. )
  12. func init() {
  13. VerifierMap.Store(data.KeyTypeECDSA_SHA2_P256, NewEcdsaVerifier)
  14. }
  15. func NewEcdsaVerifier() Verifier {
  16. return &p256Verifier{}
  17. }
  18. type ecdsaSignature struct {
  19. R, S *big.Int
  20. }
  21. type p256Verifier struct {
  22. PublicKey data.HexBytes `json:"public"`
  23. key *data.PublicKey
  24. }
  25. func (p *p256Verifier) Public() string {
  26. return p.PublicKey.String()
  27. }
  28. func (p *p256Verifier) Verify(msg, sigBytes []byte) error {
  29. x, y := elliptic.Unmarshal(elliptic.P256(), p.PublicKey)
  30. k := &ecdsa.PublicKey{
  31. Curve: elliptic.P256(),
  32. X: x,
  33. Y: y,
  34. }
  35. var sig ecdsaSignature
  36. if _, err := asn1.Unmarshal(sigBytes, &sig); err != nil {
  37. return err
  38. }
  39. hash := sha256.Sum256(msg)
  40. if !ecdsa.Verify(k, hash[:], sig.R, sig.S) {
  41. return errors.New("tuf: ecdsa signature verification failed")
  42. }
  43. return nil
  44. }
  45. func (p *p256Verifier) MarshalPublicKey() *data.PublicKey {
  46. return p.key
  47. }
  48. func (p *p256Verifier) UnmarshalPublicKey(key *data.PublicKey) error {
  49. if err := json.Unmarshal(key.Value, p); err != nil {
  50. return err
  51. }
  52. x, _ := elliptic.Unmarshal(elliptic.P256(), p.PublicKey)
  53. if x == nil {
  54. return errors.New("tuf: invalid ecdsa public key point")
  55. }
  56. p.key = key
  57. return nil
  58. }