github.com/lestrrat-go/jwx/v2@v2.0.21/jwk/ecdsa_gen.go (about)

     1  // Code generated by tools/cmd/genjwk/main.go. DO NOT EDIT.
     2  
     3  package jwk
     4  
     5  import (
     6  	"bytes"
     7  	"context"
     8  	"crypto/ecdsa"
     9  	"fmt"
    10  	"sort"
    11  	"sync"
    12  
    13  	"github.com/lestrrat-go/iter/mapiter"
    14  	"github.com/lestrrat-go/jwx/v2/cert"
    15  	"github.com/lestrrat-go/jwx/v2/internal/base64"
    16  	"github.com/lestrrat-go/jwx/v2/internal/iter"
    17  	"github.com/lestrrat-go/jwx/v2/internal/json"
    18  	"github.com/lestrrat-go/jwx/v2/internal/pool"
    19  	"github.com/lestrrat-go/jwx/v2/jwa"
    20  )
    21  
    22  const (
    23  	ECDSACrvKey = "crv"
    24  	ECDSADKey   = "d"
    25  	ECDSAXKey   = "x"
    26  	ECDSAYKey   = "y"
    27  )
    28  
    29  type ECDSAPublicKey interface {
    30  	Key
    31  	FromRaw(*ecdsa.PublicKey) error
    32  	Crv() jwa.EllipticCurveAlgorithm
    33  	X() []byte
    34  	Y() []byte
    35  }
    36  
    37  type ecdsaPublicKey struct {
    38  	algorithm              *jwa.KeyAlgorithm // https://tools.ietf.org/html/rfc7517#section-4.4
    39  	crv                    *jwa.EllipticCurveAlgorithm
    40  	keyID                  *string           // https://tools.ietf.org/html/rfc7515#section-4.1.4
    41  	keyOps                 *KeyOperationList // https://tools.ietf.org/html/rfc7517#section-4.3
    42  	keyUsage               *string           // https://tools.ietf.org/html/rfc7517#section-4.2
    43  	x                      []byte
    44  	x509CertChain          *cert.Chain // https://tools.ietf.org/html/rfc7515#section-4.1.6
    45  	x509CertThumbprint     *string     // https://tools.ietf.org/html/rfc7515#section-4.1.7
    46  	x509CertThumbprintS256 *string     // https://tools.ietf.org/html/rfc7515#section-4.1.8
    47  	x509URL                *string     // https://tools.ietf.org/html/rfc7515#section-4.1.5
    48  	y                      []byte
    49  	privateParams          map[string]interface{}
    50  	mu                     *sync.RWMutex
    51  	dc                     json.DecodeCtx
    52  }
    53  
    54  var _ ECDSAPublicKey = &ecdsaPublicKey{}
    55  var _ Key = &ecdsaPublicKey{}
    56  
    57  func newECDSAPublicKey() *ecdsaPublicKey {
    58  	return &ecdsaPublicKey{
    59  		mu:            &sync.RWMutex{},
    60  		privateParams: make(map[string]interface{}),
    61  	}
    62  }
    63  
    64  func (h ecdsaPublicKey) KeyType() jwa.KeyType {
    65  	return jwa.EC
    66  }
    67  
    68  func (h ecdsaPublicKey) IsPrivate() bool {
    69  	return false
    70  }
    71  
    72  func (h *ecdsaPublicKey) Algorithm() jwa.KeyAlgorithm {
    73  	if h.algorithm != nil {
    74  		return *(h.algorithm)
    75  	}
    76  	return jwa.InvalidKeyAlgorithm("")
    77  }
    78  
    79  func (h *ecdsaPublicKey) Crv() jwa.EllipticCurveAlgorithm {
    80  	if h.crv != nil {
    81  		return *(h.crv)
    82  	}
    83  	return jwa.InvalidEllipticCurve
    84  }
    85  
    86  func (h *ecdsaPublicKey) KeyID() string {
    87  	if h.keyID != nil {
    88  		return *(h.keyID)
    89  	}
    90  	return ""
    91  }
    92  
    93  func (h *ecdsaPublicKey) KeyOps() KeyOperationList {
    94  	if h.keyOps != nil {
    95  		return *(h.keyOps)
    96  	}
    97  	return nil
    98  }
    99  
   100  func (h *ecdsaPublicKey) KeyUsage() string {
   101  	if h.keyUsage != nil {
   102  		return *(h.keyUsage)
   103  	}
   104  	return ""
   105  }
   106  
   107  func (h *ecdsaPublicKey) X() []byte {
   108  	return h.x
   109  }
   110  
   111  func (h *ecdsaPublicKey) X509CertChain() *cert.Chain {
   112  	return h.x509CertChain
   113  }
   114  
   115  func (h *ecdsaPublicKey) X509CertThumbprint() string {
   116  	if h.x509CertThumbprint != nil {
   117  		return *(h.x509CertThumbprint)
   118  	}
   119  	return ""
   120  }
   121  
   122  func (h *ecdsaPublicKey) X509CertThumbprintS256() string {
   123  	if h.x509CertThumbprintS256 != nil {
   124  		return *(h.x509CertThumbprintS256)
   125  	}
   126  	return ""
   127  }
   128  
   129  func (h *ecdsaPublicKey) X509URL() string {
   130  	if h.x509URL != nil {
   131  		return *(h.x509URL)
   132  	}
   133  	return ""
   134  }
   135  
   136  func (h *ecdsaPublicKey) Y() []byte {
   137  	return h.y
   138  }
   139  
   140  func (h *ecdsaPublicKey) makePairs() []*HeaderPair {
   141  	h.mu.RLock()
   142  	defer h.mu.RUnlock()
   143  
   144  	var pairs []*HeaderPair
   145  	pairs = append(pairs, &HeaderPair{Key: "kty", Value: jwa.EC})
   146  	if h.algorithm != nil {
   147  		pairs = append(pairs, &HeaderPair{Key: AlgorithmKey, Value: *(h.algorithm)})
   148  	}
   149  	if h.crv != nil {
   150  		pairs = append(pairs, &HeaderPair{Key: ECDSACrvKey, Value: *(h.crv)})
   151  	}
   152  	if h.keyID != nil {
   153  		pairs = append(pairs, &HeaderPair{Key: KeyIDKey, Value: *(h.keyID)})
   154  	}
   155  	if h.keyOps != nil {
   156  		pairs = append(pairs, &HeaderPair{Key: KeyOpsKey, Value: *(h.keyOps)})
   157  	}
   158  	if h.keyUsage != nil {
   159  		pairs = append(pairs, &HeaderPair{Key: KeyUsageKey, Value: *(h.keyUsage)})
   160  	}
   161  	if h.x != nil {
   162  		pairs = append(pairs, &HeaderPair{Key: ECDSAXKey, Value: h.x})
   163  	}
   164  	if h.x509CertChain != nil {
   165  		pairs = append(pairs, &HeaderPair{Key: X509CertChainKey, Value: h.x509CertChain})
   166  	}
   167  	if h.x509CertThumbprint != nil {
   168  		pairs = append(pairs, &HeaderPair{Key: X509CertThumbprintKey, Value: *(h.x509CertThumbprint)})
   169  	}
   170  	if h.x509CertThumbprintS256 != nil {
   171  		pairs = append(pairs, &HeaderPair{Key: X509CertThumbprintS256Key, Value: *(h.x509CertThumbprintS256)})
   172  	}
   173  	if h.x509URL != nil {
   174  		pairs = append(pairs, &HeaderPair{Key: X509URLKey, Value: *(h.x509URL)})
   175  	}
   176  	if h.y != nil {
   177  		pairs = append(pairs, &HeaderPair{Key: ECDSAYKey, Value: h.y})
   178  	}
   179  	for k, v := range h.privateParams {
   180  		pairs = append(pairs, &HeaderPair{Key: k, Value: v})
   181  	}
   182  	return pairs
   183  }
   184  
   185  func (h *ecdsaPublicKey) PrivateParams() map[string]interface{} {
   186  	return h.privateParams
   187  }
   188  
   189  func (h *ecdsaPublicKey) Get(name string) (interface{}, bool) {
   190  	h.mu.RLock()
   191  	defer h.mu.RUnlock()
   192  	switch name {
   193  	case KeyTypeKey:
   194  		return h.KeyType(), true
   195  	case AlgorithmKey:
   196  		if h.algorithm == nil {
   197  			return nil, false
   198  		}
   199  		return *(h.algorithm), true
   200  	case ECDSACrvKey:
   201  		if h.crv == nil {
   202  			return nil, false
   203  		}
   204  		return *(h.crv), true
   205  	case KeyIDKey:
   206  		if h.keyID == nil {
   207  			return nil, false
   208  		}
   209  		return *(h.keyID), true
   210  	case KeyOpsKey:
   211  		if h.keyOps == nil {
   212  			return nil, false
   213  		}
   214  		return *(h.keyOps), true
   215  	case KeyUsageKey:
   216  		if h.keyUsage == nil {
   217  			return nil, false
   218  		}
   219  		return *(h.keyUsage), true
   220  	case ECDSAXKey:
   221  		if h.x == nil {
   222  			return nil, false
   223  		}
   224  		return h.x, true
   225  	case X509CertChainKey:
   226  		if h.x509CertChain == nil {
   227  			return nil, false
   228  		}
   229  		return h.x509CertChain, true
   230  	case X509CertThumbprintKey:
   231  		if h.x509CertThumbprint == nil {
   232  			return nil, false
   233  		}
   234  		return *(h.x509CertThumbprint), true
   235  	case X509CertThumbprintS256Key:
   236  		if h.x509CertThumbprintS256 == nil {
   237  			return nil, false
   238  		}
   239  		return *(h.x509CertThumbprintS256), true
   240  	case X509URLKey:
   241  		if h.x509URL == nil {
   242  			return nil, false
   243  		}
   244  		return *(h.x509URL), true
   245  	case ECDSAYKey:
   246  		if h.y == nil {
   247  			return nil, false
   248  		}
   249  		return h.y, true
   250  	default:
   251  		v, ok := h.privateParams[name]
   252  		return v, ok
   253  	}
   254  }
   255  
   256  func (h *ecdsaPublicKey) Set(name string, value interface{}) error {
   257  	h.mu.Lock()
   258  	defer h.mu.Unlock()
   259  	return h.setNoLock(name, value)
   260  }
   261  
   262  func (h *ecdsaPublicKey) setNoLock(name string, value interface{}) error {
   263  	switch name {
   264  	case "kty":
   265  		return nil
   266  	case AlgorithmKey:
   267  		switch v := value.(type) {
   268  		case string, jwa.SignatureAlgorithm, jwa.ContentEncryptionAlgorithm:
   269  			var tmp = jwa.KeyAlgorithmFrom(v)
   270  			h.algorithm = &tmp
   271  		case fmt.Stringer:
   272  			s := v.String()
   273  			var tmp = jwa.KeyAlgorithmFrom(s)
   274  			h.algorithm = &tmp
   275  		default:
   276  			return fmt.Errorf(`invalid type for %s key: %T`, AlgorithmKey, value)
   277  		}
   278  		return nil
   279  	case ECDSACrvKey:
   280  		if v, ok := value.(jwa.EllipticCurveAlgorithm); ok {
   281  			h.crv = &v
   282  			return nil
   283  		}
   284  		return fmt.Errorf(`invalid value for %s key: %T`, ECDSACrvKey, value)
   285  	case KeyIDKey:
   286  		if v, ok := value.(string); ok {
   287  			h.keyID = &v
   288  			return nil
   289  		}
   290  		return fmt.Errorf(`invalid value for %s key: %T`, KeyIDKey, value)
   291  	case KeyOpsKey:
   292  		var acceptor KeyOperationList
   293  		if err := acceptor.Accept(value); err != nil {
   294  			return fmt.Errorf(`invalid value for %s key: %w`, KeyOpsKey, err)
   295  		}
   296  		h.keyOps = &acceptor
   297  		return nil
   298  	case KeyUsageKey:
   299  		switch v := value.(type) {
   300  		case KeyUsageType:
   301  			switch v {
   302  			case ForSignature, ForEncryption:
   303  				tmp := v.String()
   304  				h.keyUsage = &tmp
   305  			default:
   306  				return fmt.Errorf(`invalid key usage type %s`, v)
   307  			}
   308  		case string:
   309  			h.keyUsage = &v
   310  		default:
   311  			return fmt.Errorf(`invalid key usage type %s`, v)
   312  		}
   313  	case ECDSAXKey:
   314  		if v, ok := value.([]byte); ok {
   315  			h.x = v
   316  			return nil
   317  		}
   318  		return fmt.Errorf(`invalid value for %s key: %T`, ECDSAXKey, value)
   319  	case X509CertChainKey:
   320  		if v, ok := value.(*cert.Chain); ok {
   321  			h.x509CertChain = v
   322  			return nil
   323  		}
   324  		return fmt.Errorf(`invalid value for %s key: %T`, X509CertChainKey, value)
   325  	case X509CertThumbprintKey:
   326  		if v, ok := value.(string); ok {
   327  			h.x509CertThumbprint = &v
   328  			return nil
   329  		}
   330  		return fmt.Errorf(`invalid value for %s key: %T`, X509CertThumbprintKey, value)
   331  	case X509CertThumbprintS256Key:
   332  		if v, ok := value.(string); ok {
   333  			h.x509CertThumbprintS256 = &v
   334  			return nil
   335  		}
   336  		return fmt.Errorf(`invalid value for %s key: %T`, X509CertThumbprintS256Key, value)
   337  	case X509URLKey:
   338  		if v, ok := value.(string); ok {
   339  			h.x509URL = &v
   340  			return nil
   341  		}
   342  		return fmt.Errorf(`invalid value for %s key: %T`, X509URLKey, value)
   343  	case ECDSAYKey:
   344  		if v, ok := value.([]byte); ok {
   345  			h.y = v
   346  			return nil
   347  		}
   348  		return fmt.Errorf(`invalid value for %s key: %T`, ECDSAYKey, value)
   349  	default:
   350  		if h.privateParams == nil {
   351  			h.privateParams = map[string]interface{}{}
   352  		}
   353  		h.privateParams[name] = value
   354  	}
   355  	return nil
   356  }
   357  
   358  func (k *ecdsaPublicKey) Remove(key string) error {
   359  	k.mu.Lock()
   360  	defer k.mu.Unlock()
   361  	switch key {
   362  	case AlgorithmKey:
   363  		k.algorithm = nil
   364  	case ECDSACrvKey:
   365  		k.crv = nil
   366  	case KeyIDKey:
   367  		k.keyID = nil
   368  	case KeyOpsKey:
   369  		k.keyOps = nil
   370  	case KeyUsageKey:
   371  		k.keyUsage = nil
   372  	case ECDSAXKey:
   373  		k.x = nil
   374  	case X509CertChainKey:
   375  		k.x509CertChain = nil
   376  	case X509CertThumbprintKey:
   377  		k.x509CertThumbprint = nil
   378  	case X509CertThumbprintS256Key:
   379  		k.x509CertThumbprintS256 = nil
   380  	case X509URLKey:
   381  		k.x509URL = nil
   382  	case ECDSAYKey:
   383  		k.y = nil
   384  	default:
   385  		delete(k.privateParams, key)
   386  	}
   387  	return nil
   388  }
   389  
   390  func (k *ecdsaPublicKey) Clone() (Key, error) {
   391  	return cloneKey(k)
   392  }
   393  
   394  func (k *ecdsaPublicKey) DecodeCtx() json.DecodeCtx {
   395  	k.mu.RLock()
   396  	defer k.mu.RUnlock()
   397  	return k.dc
   398  }
   399  
   400  func (k *ecdsaPublicKey) SetDecodeCtx(dc json.DecodeCtx) {
   401  	k.mu.Lock()
   402  	defer k.mu.Unlock()
   403  	k.dc = dc
   404  }
   405  
   406  func (h *ecdsaPublicKey) UnmarshalJSON(buf []byte) error {
   407  	h.mu.Lock()
   408  	defer h.mu.Unlock()
   409  	h.algorithm = nil
   410  	h.crv = nil
   411  	h.keyID = nil
   412  	h.keyOps = nil
   413  	h.keyUsage = nil
   414  	h.x = nil
   415  	h.x509CertChain = nil
   416  	h.x509CertThumbprint = nil
   417  	h.x509CertThumbprintS256 = nil
   418  	h.x509URL = nil
   419  	h.y = nil
   420  	dec := json.NewDecoder(bytes.NewReader(buf))
   421  LOOP:
   422  	for {
   423  		tok, err := dec.Token()
   424  		if err != nil {
   425  			return fmt.Errorf(`error reading token: %w`, err)
   426  		}
   427  		switch tok := tok.(type) {
   428  		case json.Delim:
   429  			// Assuming we're doing everything correctly, we should ONLY
   430  			// get either '{' or '}' here.
   431  			if tok == '}' { // End of object
   432  				break LOOP
   433  			} else if tok != '{' {
   434  				return fmt.Errorf(`expected '{', but got '%c'`, tok)
   435  			}
   436  		case string: // Objects can only have string keys
   437  			switch tok {
   438  			case KeyTypeKey:
   439  				val, err := json.ReadNextStringToken(dec)
   440  				if err != nil {
   441  					return fmt.Errorf(`error reading token: %w`, err)
   442  				}
   443  				if val != jwa.EC.String() {
   444  					return fmt.Errorf(`invalid kty value for RSAPublicKey (%s)`, val)
   445  				}
   446  			case AlgorithmKey:
   447  				var s string
   448  				if err := dec.Decode(&s); err != nil {
   449  					return fmt.Errorf(`failed to decode value for key %s: %w`, AlgorithmKey, err)
   450  				}
   451  				alg := jwa.KeyAlgorithmFrom(s)
   452  				h.algorithm = &alg
   453  			case ECDSACrvKey:
   454  				var decoded jwa.EllipticCurveAlgorithm
   455  				if err := dec.Decode(&decoded); err != nil {
   456  					return fmt.Errorf(`failed to decode value for key %s: %w`, ECDSACrvKey, err)
   457  				}
   458  				h.crv = &decoded
   459  			case KeyIDKey:
   460  				if err := json.AssignNextStringToken(&h.keyID, dec); err != nil {
   461  					return fmt.Errorf(`failed to decode value for key %s: %w`, KeyIDKey, err)
   462  				}
   463  			case KeyOpsKey:
   464  				var decoded KeyOperationList
   465  				if err := dec.Decode(&decoded); err != nil {
   466  					return fmt.Errorf(`failed to decode value for key %s: %w`, KeyOpsKey, err)
   467  				}
   468  				h.keyOps = &decoded
   469  			case KeyUsageKey:
   470  				if err := json.AssignNextStringToken(&h.keyUsage, dec); err != nil {
   471  					return fmt.Errorf(`failed to decode value for key %s: %w`, KeyUsageKey, err)
   472  				}
   473  			case ECDSAXKey:
   474  				if err := json.AssignNextBytesToken(&h.x, dec); err != nil {
   475  					return fmt.Errorf(`failed to decode value for key %s: %w`, ECDSAXKey, err)
   476  				}
   477  			case X509CertChainKey:
   478  				var decoded cert.Chain
   479  				if err := dec.Decode(&decoded); err != nil {
   480  					return fmt.Errorf(`failed to decode value for key %s: %w`, X509CertChainKey, err)
   481  				}
   482  				h.x509CertChain = &decoded
   483  			case X509CertThumbprintKey:
   484  				if err := json.AssignNextStringToken(&h.x509CertThumbprint, dec); err != nil {
   485  					return fmt.Errorf(`failed to decode value for key %s: %w`, X509CertThumbprintKey, err)
   486  				}
   487  			case X509CertThumbprintS256Key:
   488  				if err := json.AssignNextStringToken(&h.x509CertThumbprintS256, dec); err != nil {
   489  					return fmt.Errorf(`failed to decode value for key %s: %w`, X509CertThumbprintS256Key, err)
   490  				}
   491  			case X509URLKey:
   492  				if err := json.AssignNextStringToken(&h.x509URL, dec); err != nil {
   493  					return fmt.Errorf(`failed to decode value for key %s: %w`, X509URLKey, err)
   494  				}
   495  			case ECDSAYKey:
   496  				if err := json.AssignNextBytesToken(&h.y, dec); err != nil {
   497  					return fmt.Errorf(`failed to decode value for key %s: %w`, ECDSAYKey, err)
   498  				}
   499  			default:
   500  				if dc := h.dc; dc != nil {
   501  					if localReg := dc.Registry(); localReg != nil {
   502  						decoded, err := localReg.Decode(dec, tok)
   503  						if err == nil {
   504  							h.setNoLock(tok, decoded)
   505  							continue
   506  						}
   507  					}
   508  				}
   509  				decoded, err := registry.Decode(dec, tok)
   510  				if err == nil {
   511  					h.setNoLock(tok, decoded)
   512  					continue
   513  				}
   514  				return fmt.Errorf(`could not decode field %s: %w`, tok, err)
   515  			}
   516  		default:
   517  			return fmt.Errorf(`invalid token %T`, tok)
   518  		}
   519  	}
   520  	if h.crv == nil {
   521  		return fmt.Errorf(`required field crv is missing`)
   522  	}
   523  	if h.x == nil {
   524  		return fmt.Errorf(`required field x is missing`)
   525  	}
   526  	if h.y == nil {
   527  		return fmt.Errorf(`required field y is missing`)
   528  	}
   529  	return nil
   530  }
   531  
   532  func (h ecdsaPublicKey) MarshalJSON() ([]byte, error) {
   533  	data := make(map[string]interface{})
   534  	fields := make([]string, 0, 11)
   535  	for _, pair := range h.makePairs() {
   536  		fields = append(fields, pair.Key.(string))
   537  		data[pair.Key.(string)] = pair.Value
   538  	}
   539  
   540  	sort.Strings(fields)
   541  	buf := pool.GetBytesBuffer()
   542  	defer pool.ReleaseBytesBuffer(buf)
   543  	buf.WriteByte('{')
   544  	enc := json.NewEncoder(buf)
   545  	for i, f := range fields {
   546  		if i > 0 {
   547  			buf.WriteRune(',')
   548  		}
   549  		buf.WriteRune('"')
   550  		buf.WriteString(f)
   551  		buf.WriteString(`":`)
   552  		v := data[f]
   553  		switch v := v.(type) {
   554  		case []byte:
   555  			buf.WriteRune('"')
   556  			buf.WriteString(base64.EncodeToString(v))
   557  			buf.WriteRune('"')
   558  		default:
   559  			if err := enc.Encode(v); err != nil {
   560  				return nil, fmt.Errorf(`failed to encode value for field %s: %w`, f, err)
   561  			}
   562  			buf.Truncate(buf.Len() - 1)
   563  		}
   564  	}
   565  	buf.WriteByte('}')
   566  	ret := make([]byte, buf.Len())
   567  	copy(ret, buf.Bytes())
   568  	return ret, nil
   569  }
   570  
   571  func (h *ecdsaPublicKey) Iterate(ctx context.Context) HeaderIterator {
   572  	pairs := h.makePairs()
   573  	ch := make(chan *HeaderPair, len(pairs))
   574  	go func(ctx context.Context, ch chan *HeaderPair, pairs []*HeaderPair) {
   575  		defer close(ch)
   576  		for _, pair := range pairs {
   577  			select {
   578  			case <-ctx.Done():
   579  				return
   580  			case ch <- pair:
   581  			}
   582  		}
   583  	}(ctx, ch, pairs)
   584  	return mapiter.New(ch)
   585  }
   586  
   587  func (h *ecdsaPublicKey) Walk(ctx context.Context, visitor HeaderVisitor) error {
   588  	return iter.WalkMap(ctx, h, visitor)
   589  }
   590  
   591  func (h *ecdsaPublicKey) AsMap(ctx context.Context) (map[string]interface{}, error) {
   592  	return iter.AsMap(ctx, h)
   593  }
   594  
   595  type ECDSAPrivateKey interface {
   596  	Key
   597  	FromRaw(*ecdsa.PrivateKey) error
   598  	Crv() jwa.EllipticCurveAlgorithm
   599  	D() []byte
   600  	X() []byte
   601  	Y() []byte
   602  }
   603  
   604  type ecdsaPrivateKey struct {
   605  	algorithm              *jwa.KeyAlgorithm // https://tools.ietf.org/html/rfc7517#section-4.4
   606  	crv                    *jwa.EllipticCurveAlgorithm
   607  	d                      []byte
   608  	keyID                  *string           // https://tools.ietf.org/html/rfc7515#section-4.1.4
   609  	keyOps                 *KeyOperationList // https://tools.ietf.org/html/rfc7517#section-4.3
   610  	keyUsage               *string           // https://tools.ietf.org/html/rfc7517#section-4.2
   611  	x                      []byte
   612  	x509CertChain          *cert.Chain // https://tools.ietf.org/html/rfc7515#section-4.1.6
   613  	x509CertThumbprint     *string     // https://tools.ietf.org/html/rfc7515#section-4.1.7
   614  	x509CertThumbprintS256 *string     // https://tools.ietf.org/html/rfc7515#section-4.1.8
   615  	x509URL                *string     // https://tools.ietf.org/html/rfc7515#section-4.1.5
   616  	y                      []byte
   617  	privateParams          map[string]interface{}
   618  	mu                     *sync.RWMutex
   619  	dc                     json.DecodeCtx
   620  }
   621  
   622  var _ ECDSAPrivateKey = &ecdsaPrivateKey{}
   623  var _ Key = &ecdsaPrivateKey{}
   624  
   625  func newECDSAPrivateKey() *ecdsaPrivateKey {
   626  	return &ecdsaPrivateKey{
   627  		mu:            &sync.RWMutex{},
   628  		privateParams: make(map[string]interface{}),
   629  	}
   630  }
   631  
   632  func (h ecdsaPrivateKey) KeyType() jwa.KeyType {
   633  	return jwa.EC
   634  }
   635  
   636  func (h ecdsaPrivateKey) IsPrivate() bool {
   637  	return true
   638  }
   639  
   640  func (h *ecdsaPrivateKey) Algorithm() jwa.KeyAlgorithm {
   641  	if h.algorithm != nil {
   642  		return *(h.algorithm)
   643  	}
   644  	return jwa.InvalidKeyAlgorithm("")
   645  }
   646  
   647  func (h *ecdsaPrivateKey) Crv() jwa.EllipticCurveAlgorithm {
   648  	if h.crv != nil {
   649  		return *(h.crv)
   650  	}
   651  	return jwa.InvalidEllipticCurve
   652  }
   653  
   654  func (h *ecdsaPrivateKey) D() []byte {
   655  	return h.d
   656  }
   657  
   658  func (h *ecdsaPrivateKey) KeyID() string {
   659  	if h.keyID != nil {
   660  		return *(h.keyID)
   661  	}
   662  	return ""
   663  }
   664  
   665  func (h *ecdsaPrivateKey) KeyOps() KeyOperationList {
   666  	if h.keyOps != nil {
   667  		return *(h.keyOps)
   668  	}
   669  	return nil
   670  }
   671  
   672  func (h *ecdsaPrivateKey) KeyUsage() string {
   673  	if h.keyUsage != nil {
   674  		return *(h.keyUsage)
   675  	}
   676  	return ""
   677  }
   678  
   679  func (h *ecdsaPrivateKey) X() []byte {
   680  	return h.x
   681  }
   682  
   683  func (h *ecdsaPrivateKey) X509CertChain() *cert.Chain {
   684  	return h.x509CertChain
   685  }
   686  
   687  func (h *ecdsaPrivateKey) X509CertThumbprint() string {
   688  	if h.x509CertThumbprint != nil {
   689  		return *(h.x509CertThumbprint)
   690  	}
   691  	return ""
   692  }
   693  
   694  func (h *ecdsaPrivateKey) X509CertThumbprintS256() string {
   695  	if h.x509CertThumbprintS256 != nil {
   696  		return *(h.x509CertThumbprintS256)
   697  	}
   698  	return ""
   699  }
   700  
   701  func (h *ecdsaPrivateKey) X509URL() string {
   702  	if h.x509URL != nil {
   703  		return *(h.x509URL)
   704  	}
   705  	return ""
   706  }
   707  
   708  func (h *ecdsaPrivateKey) Y() []byte {
   709  	return h.y
   710  }
   711  
   712  func (h *ecdsaPrivateKey) makePairs() []*HeaderPair {
   713  	h.mu.RLock()
   714  	defer h.mu.RUnlock()
   715  
   716  	var pairs []*HeaderPair
   717  	pairs = append(pairs, &HeaderPair{Key: "kty", Value: jwa.EC})
   718  	if h.algorithm != nil {
   719  		pairs = append(pairs, &HeaderPair{Key: AlgorithmKey, Value: *(h.algorithm)})
   720  	}
   721  	if h.crv != nil {
   722  		pairs = append(pairs, &HeaderPair{Key: ECDSACrvKey, Value: *(h.crv)})
   723  	}
   724  	if h.d != nil {
   725  		pairs = append(pairs, &HeaderPair{Key: ECDSADKey, Value: h.d})
   726  	}
   727  	if h.keyID != nil {
   728  		pairs = append(pairs, &HeaderPair{Key: KeyIDKey, Value: *(h.keyID)})
   729  	}
   730  	if h.keyOps != nil {
   731  		pairs = append(pairs, &HeaderPair{Key: KeyOpsKey, Value: *(h.keyOps)})
   732  	}
   733  	if h.keyUsage != nil {
   734  		pairs = append(pairs, &HeaderPair{Key: KeyUsageKey, Value: *(h.keyUsage)})
   735  	}
   736  	if h.x != nil {
   737  		pairs = append(pairs, &HeaderPair{Key: ECDSAXKey, Value: h.x})
   738  	}
   739  	if h.x509CertChain != nil {
   740  		pairs = append(pairs, &HeaderPair{Key: X509CertChainKey, Value: h.x509CertChain})
   741  	}
   742  	if h.x509CertThumbprint != nil {
   743  		pairs = append(pairs, &HeaderPair{Key: X509CertThumbprintKey, Value: *(h.x509CertThumbprint)})
   744  	}
   745  	if h.x509CertThumbprintS256 != nil {
   746  		pairs = append(pairs, &HeaderPair{Key: X509CertThumbprintS256Key, Value: *(h.x509CertThumbprintS256)})
   747  	}
   748  	if h.x509URL != nil {
   749  		pairs = append(pairs, &HeaderPair{Key: X509URLKey, Value: *(h.x509URL)})
   750  	}
   751  	if h.y != nil {
   752  		pairs = append(pairs, &HeaderPair{Key: ECDSAYKey, Value: h.y})
   753  	}
   754  	for k, v := range h.privateParams {
   755  		pairs = append(pairs, &HeaderPair{Key: k, Value: v})
   756  	}
   757  	return pairs
   758  }
   759  
   760  func (h *ecdsaPrivateKey) PrivateParams() map[string]interface{} {
   761  	return h.privateParams
   762  }
   763  
   764  func (h *ecdsaPrivateKey) Get(name string) (interface{}, bool) {
   765  	h.mu.RLock()
   766  	defer h.mu.RUnlock()
   767  	switch name {
   768  	case KeyTypeKey:
   769  		return h.KeyType(), true
   770  	case AlgorithmKey:
   771  		if h.algorithm == nil {
   772  			return nil, false
   773  		}
   774  		return *(h.algorithm), true
   775  	case ECDSACrvKey:
   776  		if h.crv == nil {
   777  			return nil, false
   778  		}
   779  		return *(h.crv), true
   780  	case ECDSADKey:
   781  		if h.d == nil {
   782  			return nil, false
   783  		}
   784  		return h.d, true
   785  	case KeyIDKey:
   786  		if h.keyID == nil {
   787  			return nil, false
   788  		}
   789  		return *(h.keyID), true
   790  	case KeyOpsKey:
   791  		if h.keyOps == nil {
   792  			return nil, false
   793  		}
   794  		return *(h.keyOps), true
   795  	case KeyUsageKey:
   796  		if h.keyUsage == nil {
   797  			return nil, false
   798  		}
   799  		return *(h.keyUsage), true
   800  	case ECDSAXKey:
   801  		if h.x == nil {
   802  			return nil, false
   803  		}
   804  		return h.x, true
   805  	case X509CertChainKey:
   806  		if h.x509CertChain == nil {
   807  			return nil, false
   808  		}
   809  		return h.x509CertChain, true
   810  	case X509CertThumbprintKey:
   811  		if h.x509CertThumbprint == nil {
   812  			return nil, false
   813  		}
   814  		return *(h.x509CertThumbprint), true
   815  	case X509CertThumbprintS256Key:
   816  		if h.x509CertThumbprintS256 == nil {
   817  			return nil, false
   818  		}
   819  		return *(h.x509CertThumbprintS256), true
   820  	case X509URLKey:
   821  		if h.x509URL == nil {
   822  			return nil, false
   823  		}
   824  		return *(h.x509URL), true
   825  	case ECDSAYKey:
   826  		if h.y == nil {
   827  			return nil, false
   828  		}
   829  		return h.y, true
   830  	default:
   831  		v, ok := h.privateParams[name]
   832  		return v, ok
   833  	}
   834  }
   835  
   836  func (h *ecdsaPrivateKey) Set(name string, value interface{}) error {
   837  	h.mu.Lock()
   838  	defer h.mu.Unlock()
   839  	return h.setNoLock(name, value)
   840  }
   841  
   842  func (h *ecdsaPrivateKey) setNoLock(name string, value interface{}) error {
   843  	switch name {
   844  	case "kty":
   845  		return nil
   846  	case AlgorithmKey:
   847  		switch v := value.(type) {
   848  		case string, jwa.SignatureAlgorithm, jwa.ContentEncryptionAlgorithm:
   849  			var tmp = jwa.KeyAlgorithmFrom(v)
   850  			h.algorithm = &tmp
   851  		case fmt.Stringer:
   852  			s := v.String()
   853  			var tmp = jwa.KeyAlgorithmFrom(s)
   854  			h.algorithm = &tmp
   855  		default:
   856  			return fmt.Errorf(`invalid type for %s key: %T`, AlgorithmKey, value)
   857  		}
   858  		return nil
   859  	case ECDSACrvKey:
   860  		if v, ok := value.(jwa.EllipticCurveAlgorithm); ok {
   861  			h.crv = &v
   862  			return nil
   863  		}
   864  		return fmt.Errorf(`invalid value for %s key: %T`, ECDSACrvKey, value)
   865  	case ECDSADKey:
   866  		if v, ok := value.([]byte); ok {
   867  			h.d = v
   868  			return nil
   869  		}
   870  		return fmt.Errorf(`invalid value for %s key: %T`, ECDSADKey, value)
   871  	case KeyIDKey:
   872  		if v, ok := value.(string); ok {
   873  			h.keyID = &v
   874  			return nil
   875  		}
   876  		return fmt.Errorf(`invalid value for %s key: %T`, KeyIDKey, value)
   877  	case KeyOpsKey:
   878  		var acceptor KeyOperationList
   879  		if err := acceptor.Accept(value); err != nil {
   880  			return fmt.Errorf(`invalid value for %s key: %w`, KeyOpsKey, err)
   881  		}
   882  		h.keyOps = &acceptor
   883  		return nil
   884  	case KeyUsageKey:
   885  		switch v := value.(type) {
   886  		case KeyUsageType:
   887  			switch v {
   888  			case ForSignature, ForEncryption:
   889  				tmp := v.String()
   890  				h.keyUsage = &tmp
   891  			default:
   892  				return fmt.Errorf(`invalid key usage type %s`, v)
   893  			}
   894  		case string:
   895  			h.keyUsage = &v
   896  		default:
   897  			return fmt.Errorf(`invalid key usage type %s`, v)
   898  		}
   899  	case ECDSAXKey:
   900  		if v, ok := value.([]byte); ok {
   901  			h.x = v
   902  			return nil
   903  		}
   904  		return fmt.Errorf(`invalid value for %s key: %T`, ECDSAXKey, value)
   905  	case X509CertChainKey:
   906  		if v, ok := value.(*cert.Chain); ok {
   907  			h.x509CertChain = v
   908  			return nil
   909  		}
   910  		return fmt.Errorf(`invalid value for %s key: %T`, X509CertChainKey, value)
   911  	case X509CertThumbprintKey:
   912  		if v, ok := value.(string); ok {
   913  			h.x509CertThumbprint = &v
   914  			return nil
   915  		}
   916  		return fmt.Errorf(`invalid value for %s key: %T`, X509CertThumbprintKey, value)
   917  	case X509CertThumbprintS256Key:
   918  		if v, ok := value.(string); ok {
   919  			h.x509CertThumbprintS256 = &v
   920  			return nil
   921  		}
   922  		return fmt.Errorf(`invalid value for %s key: %T`, X509CertThumbprintS256Key, value)
   923  	case X509URLKey:
   924  		if v, ok := value.(string); ok {
   925  			h.x509URL = &v
   926  			return nil
   927  		}
   928  		return fmt.Errorf(`invalid value for %s key: %T`, X509URLKey, value)
   929  	case ECDSAYKey:
   930  		if v, ok := value.([]byte); ok {
   931  			h.y = v
   932  			return nil
   933  		}
   934  		return fmt.Errorf(`invalid value for %s key: %T`, ECDSAYKey, value)
   935  	default:
   936  		if h.privateParams == nil {
   937  			h.privateParams = map[string]interface{}{}
   938  		}
   939  		h.privateParams[name] = value
   940  	}
   941  	return nil
   942  }
   943  
   944  func (k *ecdsaPrivateKey) Remove(key string) error {
   945  	k.mu.Lock()
   946  	defer k.mu.Unlock()
   947  	switch key {
   948  	case AlgorithmKey:
   949  		k.algorithm = nil
   950  	case ECDSACrvKey:
   951  		k.crv = nil
   952  	case ECDSADKey:
   953  		k.d = nil
   954  	case KeyIDKey:
   955  		k.keyID = nil
   956  	case KeyOpsKey:
   957  		k.keyOps = nil
   958  	case KeyUsageKey:
   959  		k.keyUsage = nil
   960  	case ECDSAXKey:
   961  		k.x = nil
   962  	case X509CertChainKey:
   963  		k.x509CertChain = nil
   964  	case X509CertThumbprintKey:
   965  		k.x509CertThumbprint = nil
   966  	case X509CertThumbprintS256Key:
   967  		k.x509CertThumbprintS256 = nil
   968  	case X509URLKey:
   969  		k.x509URL = nil
   970  	case ECDSAYKey:
   971  		k.y = nil
   972  	default:
   973  		delete(k.privateParams, key)
   974  	}
   975  	return nil
   976  }
   977  
   978  func (k *ecdsaPrivateKey) Clone() (Key, error) {
   979  	return cloneKey(k)
   980  }
   981  
   982  func (k *ecdsaPrivateKey) DecodeCtx() json.DecodeCtx {
   983  	k.mu.RLock()
   984  	defer k.mu.RUnlock()
   985  	return k.dc
   986  }
   987  
   988  func (k *ecdsaPrivateKey) SetDecodeCtx(dc json.DecodeCtx) {
   989  	k.mu.Lock()
   990  	defer k.mu.Unlock()
   991  	k.dc = dc
   992  }
   993  
   994  func (h *ecdsaPrivateKey) UnmarshalJSON(buf []byte) error {
   995  	h.mu.Lock()
   996  	defer h.mu.Unlock()
   997  	h.algorithm = nil
   998  	h.crv = nil
   999  	h.d = nil
  1000  	h.keyID = nil
  1001  	h.keyOps = nil
  1002  	h.keyUsage = nil
  1003  	h.x = nil
  1004  	h.x509CertChain = nil
  1005  	h.x509CertThumbprint = nil
  1006  	h.x509CertThumbprintS256 = nil
  1007  	h.x509URL = nil
  1008  	h.y = nil
  1009  	dec := json.NewDecoder(bytes.NewReader(buf))
  1010  LOOP:
  1011  	for {
  1012  		tok, err := dec.Token()
  1013  		if err != nil {
  1014  			return fmt.Errorf(`error reading token: %w`, err)
  1015  		}
  1016  		switch tok := tok.(type) {
  1017  		case json.Delim:
  1018  			// Assuming we're doing everything correctly, we should ONLY
  1019  			// get either '{' or '}' here.
  1020  			if tok == '}' { // End of object
  1021  				break LOOP
  1022  			} else if tok != '{' {
  1023  				return fmt.Errorf(`expected '{', but got '%c'`, tok)
  1024  			}
  1025  		case string: // Objects can only have string keys
  1026  			switch tok {
  1027  			case KeyTypeKey:
  1028  				val, err := json.ReadNextStringToken(dec)
  1029  				if err != nil {
  1030  					return fmt.Errorf(`error reading token: %w`, err)
  1031  				}
  1032  				if val != jwa.EC.String() {
  1033  					return fmt.Errorf(`invalid kty value for RSAPublicKey (%s)`, val)
  1034  				}
  1035  			case AlgorithmKey:
  1036  				var s string
  1037  				if err := dec.Decode(&s); err != nil {
  1038  					return fmt.Errorf(`failed to decode value for key %s: %w`, AlgorithmKey, err)
  1039  				}
  1040  				alg := jwa.KeyAlgorithmFrom(s)
  1041  				h.algorithm = &alg
  1042  			case ECDSACrvKey:
  1043  				var decoded jwa.EllipticCurveAlgorithm
  1044  				if err := dec.Decode(&decoded); err != nil {
  1045  					return fmt.Errorf(`failed to decode value for key %s: %w`, ECDSACrvKey, err)
  1046  				}
  1047  				h.crv = &decoded
  1048  			case ECDSADKey:
  1049  				if err := json.AssignNextBytesToken(&h.d, dec); err != nil {
  1050  					return fmt.Errorf(`failed to decode value for key %s: %w`, ECDSADKey, err)
  1051  				}
  1052  			case KeyIDKey:
  1053  				if err := json.AssignNextStringToken(&h.keyID, dec); err != nil {
  1054  					return fmt.Errorf(`failed to decode value for key %s: %w`, KeyIDKey, err)
  1055  				}
  1056  			case KeyOpsKey:
  1057  				var decoded KeyOperationList
  1058  				if err := dec.Decode(&decoded); err != nil {
  1059  					return fmt.Errorf(`failed to decode value for key %s: %w`, KeyOpsKey, err)
  1060  				}
  1061  				h.keyOps = &decoded
  1062  			case KeyUsageKey:
  1063  				if err := json.AssignNextStringToken(&h.keyUsage, dec); err != nil {
  1064  					return fmt.Errorf(`failed to decode value for key %s: %w`, KeyUsageKey, err)
  1065  				}
  1066  			case ECDSAXKey:
  1067  				if err := json.AssignNextBytesToken(&h.x, dec); err != nil {
  1068  					return fmt.Errorf(`failed to decode value for key %s: %w`, ECDSAXKey, err)
  1069  				}
  1070  			case X509CertChainKey:
  1071  				var decoded cert.Chain
  1072  				if err := dec.Decode(&decoded); err != nil {
  1073  					return fmt.Errorf(`failed to decode value for key %s: %w`, X509CertChainKey, err)
  1074  				}
  1075  				h.x509CertChain = &decoded
  1076  			case X509CertThumbprintKey:
  1077  				if err := json.AssignNextStringToken(&h.x509CertThumbprint, dec); err != nil {
  1078  					return fmt.Errorf(`failed to decode value for key %s: %w`, X509CertThumbprintKey, err)
  1079  				}
  1080  			case X509CertThumbprintS256Key:
  1081  				if err := json.AssignNextStringToken(&h.x509CertThumbprintS256, dec); err != nil {
  1082  					return fmt.Errorf(`failed to decode value for key %s: %w`, X509CertThumbprintS256Key, err)
  1083  				}
  1084  			case X509URLKey:
  1085  				if err := json.AssignNextStringToken(&h.x509URL, dec); err != nil {
  1086  					return fmt.Errorf(`failed to decode value for key %s: %w`, X509URLKey, err)
  1087  				}
  1088  			case ECDSAYKey:
  1089  				if err := json.AssignNextBytesToken(&h.y, dec); err != nil {
  1090  					return fmt.Errorf(`failed to decode value for key %s: %w`, ECDSAYKey, err)
  1091  				}
  1092  			default:
  1093  				if dc := h.dc; dc != nil {
  1094  					if localReg := dc.Registry(); localReg != nil {
  1095  						decoded, err := localReg.Decode(dec, tok)
  1096  						if err == nil {
  1097  							h.setNoLock(tok, decoded)
  1098  							continue
  1099  						}
  1100  					}
  1101  				}
  1102  				decoded, err := registry.Decode(dec, tok)
  1103  				if err == nil {
  1104  					h.setNoLock(tok, decoded)
  1105  					continue
  1106  				}
  1107  				return fmt.Errorf(`could not decode field %s: %w`, tok, err)
  1108  			}
  1109  		default:
  1110  			return fmt.Errorf(`invalid token %T`, tok)
  1111  		}
  1112  	}
  1113  	if h.crv == nil {
  1114  		return fmt.Errorf(`required field crv is missing`)
  1115  	}
  1116  	if h.d == nil {
  1117  		return fmt.Errorf(`required field d is missing`)
  1118  	}
  1119  	if h.x == nil {
  1120  		return fmt.Errorf(`required field x is missing`)
  1121  	}
  1122  	if h.y == nil {
  1123  		return fmt.Errorf(`required field y is missing`)
  1124  	}
  1125  	return nil
  1126  }
  1127  
  1128  func (h ecdsaPrivateKey) MarshalJSON() ([]byte, error) {
  1129  	data := make(map[string]interface{})
  1130  	fields := make([]string, 0, 12)
  1131  	for _, pair := range h.makePairs() {
  1132  		fields = append(fields, pair.Key.(string))
  1133  		data[pair.Key.(string)] = pair.Value
  1134  	}
  1135  
  1136  	sort.Strings(fields)
  1137  	buf := pool.GetBytesBuffer()
  1138  	defer pool.ReleaseBytesBuffer(buf)
  1139  	buf.WriteByte('{')
  1140  	enc := json.NewEncoder(buf)
  1141  	for i, f := range fields {
  1142  		if i > 0 {
  1143  			buf.WriteRune(',')
  1144  		}
  1145  		buf.WriteRune('"')
  1146  		buf.WriteString(f)
  1147  		buf.WriteString(`":`)
  1148  		v := data[f]
  1149  		switch v := v.(type) {
  1150  		case []byte:
  1151  			buf.WriteRune('"')
  1152  			buf.WriteString(base64.EncodeToString(v))
  1153  			buf.WriteRune('"')
  1154  		default:
  1155  			if err := enc.Encode(v); err != nil {
  1156  				return nil, fmt.Errorf(`failed to encode value for field %s: %w`, f, err)
  1157  			}
  1158  			buf.Truncate(buf.Len() - 1)
  1159  		}
  1160  	}
  1161  	buf.WriteByte('}')
  1162  	ret := make([]byte, buf.Len())
  1163  	copy(ret, buf.Bytes())
  1164  	return ret, nil
  1165  }
  1166  
  1167  func (h *ecdsaPrivateKey) Iterate(ctx context.Context) HeaderIterator {
  1168  	pairs := h.makePairs()
  1169  	ch := make(chan *HeaderPair, len(pairs))
  1170  	go func(ctx context.Context, ch chan *HeaderPair, pairs []*HeaderPair) {
  1171  		defer close(ch)
  1172  		for _, pair := range pairs {
  1173  			select {
  1174  			case <-ctx.Done():
  1175  				return
  1176  			case ch <- pair:
  1177  			}
  1178  		}
  1179  	}(ctx, ch, pairs)
  1180  	return mapiter.New(ch)
  1181  }
  1182  
  1183  func (h *ecdsaPrivateKey) Walk(ctx context.Context, visitor HeaderVisitor) error {
  1184  	return iter.WalkMap(ctx, h, visitor)
  1185  }
  1186  
  1187  func (h *ecdsaPrivateKey) AsMap(ctx context.Context) (map[string]interface{}, error) {
  1188  	return iter.AsMap(ctx, h)
  1189  }