// Code generated by tools/cmd/genjwk/main.go. DO NOT EDIT.

package jwk

import (
	"bytes"
	"fmt"
	"sort"
	"sync"

	"github.com/lestrrat-go/blackmagic"
	"github.com/lestrrat-go/jwx/v3/cert"
	"github.com/lestrrat-go/jwx/v3/internal/base64"
	"github.com/lestrrat-go/jwx/v3/internal/json"
	"github.com/lestrrat-go/jwx/v3/internal/pool"
	"github.com/lestrrat-go/jwx/v3/internal/tokens"
	"github.com/lestrrat-go/jwx/v3/jwa"
	"github.com/lestrrat-go/jwx/v3/jwk/internal/registry"
)

const (
	RSADKey  = "d"
	RSADPKey = "dp"
	RSADQKey = "dq"
	RSAEKey  = "e"
	RSANKey  = "n"
	RSAPKey  = "p"
	RSAQIKey = "qi"
	RSAQKey  = "q"
)

type RSAPublicKey interface {
	Key
	E() ([]byte, bool)
	N() ([]byte, bool)
}

type rsaPublicKey struct {
	algorithm              *jwa.KeyAlgorithm // https://tools.ietf.org/html/rfc7517#section-4.4
	e                      []byte
	keyID                  *string           // https://tools.ietf.org/html/rfc7515#section-4.1.4
	keyOps                 *KeyOperationList // https://tools.ietf.org/html/rfc7517#section-4.3
	keyUsage               *string           // https://tools.ietf.org/html/rfc7517#section-4.2
	n                      []byte
	x509CertChain          *cert.Chain // https://tools.ietf.org/html/rfc7515#section-4.1.6
	x509CertThumbprint     *string     // https://tools.ietf.org/html/rfc7515#section-4.1.7
	x509CertThumbprintS256 *string     // https://tools.ietf.org/html/rfc7515#section-4.1.8
	x509URL                *string     // https://tools.ietf.org/html/rfc7515#section-4.1.5
	privateParams          map[string]any
	mu                     sync.RWMutex
	dc                     json.DecodeCtx
}

var _ RSAPublicKey = &rsaPublicKey{}
var _ Key = &rsaPublicKey{}

func newRSAPublicKey() *rsaPublicKey {
	return &rsaPublicKey{
		privateParams: make(map[string]any),
	}
}

func (h *rsaPublicKey) KeyType() jwa.KeyType {
	return jwa.RSA()
}

func (h *rsaPublicKey) rlock() {
	h.mu.RLock()
}

func (h *rsaPublicKey) runlock() {
	h.mu.RUnlock()
}

func (h *rsaPublicKey) IsPrivate() bool {
	return false
}

func (h *rsaPublicKey) Algorithm() (jwa.KeyAlgorithm, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	if h.algorithm != nil {
		return *(h.algorithm), true
	}
	return nil, false
}

func (h *rsaPublicKey) E() ([]byte, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	if h.e != nil {
		return h.e, true
	}
	return nil, false
}

func (h *rsaPublicKey) KeyID() (string, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	if h.keyID != nil {
		return *(h.keyID), true
	}
	return "", false
}

func (h *rsaPublicKey) KeyOps() (KeyOperationList, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	if h.keyOps != nil {
		return *(h.keyOps), true
	}
	return nil, false
}

func (h *rsaPublicKey) KeyUsage() (string, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	if h.keyUsage != nil {
		return *(h.keyUsage), true
	}
	return "", false
}

func (h *rsaPublicKey) N() ([]byte, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	if h.n != nil {
		return h.n, true
	}
	return nil, false
}

func (h *rsaPublicKey) X509CertChain() (*cert.Chain, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	if h.x509CertChain != nil {
		return h.x509CertChain, true
	}
	return nil, false
}

func (h *rsaPublicKey) X509CertThumbprint() (string, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	if h.x509CertThumbprint != nil {
		return *(h.x509CertThumbprint), true
	}
	return "", false
}

func (h *rsaPublicKey) X509CertThumbprintS256() (string, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	if h.x509CertThumbprintS256 != nil {
		return *(h.x509CertThumbprintS256), true
	}
	return "", false
}

func (h *rsaPublicKey) X509URL() (string, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	if h.x509URL != nil {
		return *(h.x509URL), true
	}
	return "", false
}

func (h *rsaPublicKey) Has(name string) bool {
	h.mu.RLock()
	defer h.mu.RUnlock()
	switch name {
	case KeyTypeKey:
		return true
	case AlgorithmKey:
		return h.algorithm != nil
	case RSAEKey:
		return h.e != nil
	case KeyIDKey:
		return h.keyID != nil
	case KeyOpsKey:
		return h.keyOps != nil
	case KeyUsageKey:
		return h.keyUsage != nil
	case RSANKey:
		return h.n != nil
	case X509CertChainKey:
		return h.x509CertChain != nil
	case X509CertThumbprintKey:
		return h.x509CertThumbprint != nil
	case X509CertThumbprintS256Key:
		return h.x509CertThumbprintS256 != nil
	case X509URLKey:
		return h.x509URL != nil
	default:
		_, ok := h.privateParams[name]
		return ok
	}
}

func (h *rsaPublicKey) Get(name string, dst any) error {
	h.mu.RLock()
	defer h.mu.RUnlock()
	switch name {
	case KeyTypeKey:
		if err := blackmagic.AssignIfCompatible(dst, h.KeyType()); err != nil {
			return fmt.Errorf(`rsaPublicKey.Get: failed to assign value for field %q to destination object: %w`, name, err)
		}
	case AlgorithmKey:
		if h.algorithm == nil {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, *(h.algorithm)); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
		return nil
	case RSAEKey:
		if h.e == nil {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, h.e); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
		return nil
	case KeyIDKey:
		if h.keyID == nil {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, *(h.keyID)); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
		return nil
	case KeyOpsKey:
		if h.keyOps == nil {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, *(h.keyOps)); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
		return nil
	case KeyUsageKey:
		if h.keyUsage == nil {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, *(h.keyUsage)); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
		return nil
	case RSANKey:
		if h.n == nil {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, h.n); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
		return nil
	case X509CertChainKey:
		if h.x509CertChain == nil {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, h.x509CertChain); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
		return nil
	case X509CertThumbprintKey:
		if h.x509CertThumbprint == nil {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, *(h.x509CertThumbprint)); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
		return nil
	case X509CertThumbprintS256Key:
		if h.x509CertThumbprintS256 == nil {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, *(h.x509CertThumbprintS256)); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
		return nil
	case X509URLKey:
		if h.x509URL == nil {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, *(h.x509URL)); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
		return nil
	default:
		v, ok := h.privateParams[name]
		if !ok {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, v); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
	}
	return nil
}

func (h *rsaPublicKey) Set(name string, value any) error {
	h.mu.Lock()
	defer h.mu.Unlock()
	return h.setNoLock(name, value)
}

func (h *rsaPublicKey) setNoLock(name string, value any) error {
	switch name {
	case "kty":
		return nil
	case AlgorithmKey:
		switch v := value.(type) {
		case string, jwa.SignatureAlgorithm, jwa.KeyEncryptionAlgorithm, jwa.ContentEncryptionAlgorithm:
			tmp, err := jwa.KeyAlgorithmFrom(v)
			if err != nil {
				return fmt.Errorf(`invalid algorithm for %q key: %w`, AlgorithmKey, err)
			}
			h.algorithm = &tmp
		default:
			return fmt.Errorf(`invalid type for %q key: %T`, AlgorithmKey, value)
		}
		return nil
	case RSAEKey:
		if v, ok := value.([]byte); ok {
			if v == nil {
				h.e = nil
			} else {
				h.e = make([]byte, len(v))
				copy(h.e, v)
			}
			return nil
		}
		return fmt.Errorf(`invalid value for %s key: %T`, RSAEKey, value)
	case KeyIDKey:
		if v, ok := value.(string); ok {
			h.keyID = &v
			return nil
		}
		return fmt.Errorf(`invalid value for %s key: %T`, KeyIDKey, value)
	case KeyOpsKey:
		var acceptor KeyOperationList
		if err := acceptor.Accept(value); err != nil {
			return fmt.Errorf(`invalid value for %s key: %w`, KeyOpsKey, err)
		}
		h.keyOps = &acceptor
		return nil
	case KeyUsageKey:
		switch v := value.(type) {
		case KeyUsageType:
			switch v {
			case ForSignature, ForEncryption:
				tmp := v.String()
				h.keyUsage = &tmp
			default:
				return fmt.Errorf(`invalid key usage type %s`, v)
			}
		case string:
			h.keyUsage = &v
		default:
			return fmt.Errorf(`invalid key usage type %s`, v)
		}
	case RSANKey:
		if v, ok := value.([]byte); ok {
			if v == nil {
				h.n = nil
			} else {
				h.n = make([]byte, len(v))
				copy(h.n, v)
			}
			return nil
		}
		return fmt.Errorf(`invalid value for %s key: %T`, RSANKey, value)
	case X509CertChainKey:
		if v, ok := value.(*cert.Chain); ok {
			h.x509CertChain = v
			return nil
		}
		return fmt.Errorf(`invalid value for %s key: %T`, X509CertChainKey, value)
	case X509CertThumbprintKey:
		if v, ok := value.(string); ok {
			h.x509CertThumbprint = &v
			return nil
		}
		return fmt.Errorf(`invalid value for %s key: %T`, X509CertThumbprintKey, value)
	case X509CertThumbprintS256Key:
		if v, ok := value.(string); ok {
			h.x509CertThumbprintS256 = &v
			return nil
		}
		return fmt.Errorf(`invalid value for %s key: %T`, X509CertThumbprintS256Key, value)
	case X509URLKey:
		if v, ok := value.(string); ok {
			h.x509URL = &v
			return nil
		}
		return fmt.Errorf(`invalid value for %s key: %T`, X509URLKey, value)
	default:
		if h.privateParams == nil {
			h.privateParams = map[string]any{}
		}
		h.privateParams[name] = value
	}
	return nil
}

func (k *rsaPublicKey) Remove(key string) error {
	k.mu.Lock()
	defer k.mu.Unlock()
	switch key {
	case AlgorithmKey:
		k.algorithm = nil
	case RSAEKey:
		k.e = nil
	case KeyIDKey:
		k.keyID = nil
	case KeyOpsKey:
		k.keyOps = nil
	case KeyUsageKey:
		k.keyUsage = nil
	case RSANKey:
		k.n = nil
	case X509CertChainKey:
		k.x509CertChain = nil
	case X509CertThumbprintKey:
		k.x509CertThumbprint = nil
	case X509CertThumbprintS256Key:
		k.x509CertThumbprintS256 = nil
	case X509URLKey:
		k.x509URL = nil
	default:
		delete(k.privateParams, key)
	}
	return nil
}

func (k *rsaPublicKey) Clone() (Key, error) {
	key, err := cloneKey(k)
	if err != nil {
		return nil, fmt.Errorf(`rsaPublicKey.Clone: %w`, err)
	}
	return key, nil
}

func (k *rsaPublicKey) DecodeCtx() json.DecodeCtx {
	k.mu.RLock()
	defer k.mu.RUnlock()
	return k.dc
}

func (k *rsaPublicKey) SetDecodeCtx(dc json.DecodeCtx) {
	k.mu.Lock()
	defer k.mu.Unlock()
	k.dc = dc
}

func (h *rsaPublicKey) UnmarshalJSON(buf []byte) error {
	h.mu.Lock()
	defer h.mu.Unlock()
	h.algorithm = nil
	h.e = nil
	h.keyID = nil
	h.keyOps = nil
	h.keyUsage = nil
	h.n = nil
	h.x509CertChain = nil
	h.x509CertThumbprint = nil
	h.x509CertThumbprintS256 = nil
	h.x509URL = nil
	dec := json.NewDecoder(bytes.NewReader(buf))
LOOP:
	for {
		tok, err := dec.Token()
		if err != nil {
			return fmt.Errorf(`error reading token: %w`, err)
		}
		switch tok := tok.(type) {
		case json.Delim:
			// Assuming we're doing everything correctly, we should ONLY
			// get either tokens.OpenCurlyBracket or tokens.CloseCurlyBracket here.
			if tok == tokens.CloseCurlyBracket { // End of object
				break LOOP
			} else if tok != tokens.OpenCurlyBracket {
				return fmt.Errorf(`expected '%c' but got '%c'`, tokens.OpenCurlyBracket, tok)
			}
		case string: // Objects can only have string keys
			switch tok {
			case KeyTypeKey:
				val, err := json.ReadNextStringToken(dec, h.dc)
				if err != nil {
					return fmt.Errorf(`error reading token: %w`, err)
				}
				if val != jwa.RSA().String() {
					return fmt.Errorf(`invalid kty value for RSAPublicKey (%s)`, val)
				}
			case AlgorithmKey:
				var s string
				if err := dec.Decode(&s); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, AlgorithmKey, err)
				}
				alg, err := jwa.KeyAlgorithmFrom(s)
				if err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, AlgorithmKey, err)
				}
				h.algorithm = &alg
			case RSAEKey:
				if err := json.AssignNextBytesToken(&h.e, dec); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, RSAEKey, err)
				}
			case KeyIDKey:
				if err := json.AssignNextStringToken(&h.keyID, dec, h.dc); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, KeyIDKey, err)
				}
			case KeyOpsKey:
				var decoded KeyOperationList
				if err := dec.Decode(&decoded); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, KeyOpsKey, err)
				}
				h.keyOps = &decoded
			case KeyUsageKey:
				if err := json.AssignNextStringToken(&h.keyUsage, dec, h.dc); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, KeyUsageKey, err)
				}
			case RSANKey:
				if err := json.AssignNextBytesToken(&h.n, dec); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, RSANKey, err)
				}
			case X509CertChainKey:
				var decoded cert.Chain
				if err := dec.Decode(&decoded); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, X509CertChainKey, err)
				}
				h.x509CertChain = &decoded
			case X509CertThumbprintKey:
				if err := json.AssignNextStringToken(&h.x509CertThumbprint, dec, h.dc); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, X509CertThumbprintKey, err)
				}
			case X509CertThumbprintS256Key:
				if err := json.AssignNextStringToken(&h.x509CertThumbprintS256, dec, h.dc); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, X509CertThumbprintS256Key, err)
				}
			case X509URLKey:
				if err := json.AssignNextStringToken(&h.x509URL, dec, h.dc); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, X509URLKey, err)
				}
			default:
				if dc := h.dc; dc != nil {
					if localReg := dc.Registry(); localReg != nil {
						decoded, err := localReg.Decode(dec, tok)
						if err == nil {
							h.setNoLock(tok, decoded)
							continue
						}
					}
				}
				decoded, err := fieldRegistry.Decode(dec, tok)
				if err == nil {
					h.setNoLock(tok, decoded)
					continue
				}
				return fmt.Errorf(`could not decode field %s: %w`, tok, err)
			}
		default:
			return fmt.Errorf(`invalid token %T`, tok)
		}
	}
	if h.e == nil {
		return fmt.Errorf(`required field e is missing`)
	}
	if h.n == nil {
		return fmt.Errorf(`required field n is missing`)
	}
	return nil
}

func (h *rsaPublicKey) makePairs() ([]fieldPair, error) {
	pairs := getFieldPairList()
	h.mu.RLock()
	defer h.mu.RUnlock()
	{
		v, err := json.Marshal(jwa.RSA())
		if err != nil {
			return nil, fmt.Errorf(`failed to marshal field %q: %w`, KeyTypeKey, err)
		}
		pairs = append(pairs, fieldPair{Name: KeyTypeKey, Value: v})
	}
	if h.algorithm != nil {
		v, err := json.Marshal(*(h.algorithm))
		if err != nil {
			return nil, fmt.Errorf(`failed to marshal field %q: %w`, AlgorithmKey, err)
		}
		pairs = append(pairs, fieldPair{Name: AlgorithmKey, Value: v})
	}
	if h.e != nil {
		v, err := json.Marshal(base64.EncodeToString(h.e))
		if err != nil {
			return nil, fmt.Errorf(`failed to marshal field %q: %w`, RSAEKey, err)
		}
		pairs = append(pairs, fieldPair{Name: RSAEKey, Value: v})
	}
	if h.keyID != nil {
		v, err := json.Marshal(*(h.keyID))
		if err != nil {
			return nil, fmt.Errorf(`failed to marshal field %q: %w`, KeyIDKey, err)
		}
		pairs = append(pairs, fieldPair{Name: KeyIDKey, Value: v})
	}
	if h.keyOps != nil {
		v, err := json.Marshal(*(h.keyOps))
		if err != nil {
			return nil, fmt.Errorf(`failed to marshal field %q: %w`, KeyOpsKey, err)
		}
		pairs = append(pairs, fieldPair{Name: KeyOpsKey, Value: v})
	}
	if h.keyUsage != nil {
		v, err := json.Marshal(*(h.keyUsage))
		if err != nil {
			return nil, fmt.Errorf(`failed to marshal field %q: %w`, KeyUsageKey, err)
		}
		pairs = append(pairs, fieldPair{Name: KeyUsageKey, Value: v})
	}
	if h.n != nil {
		v, err := json.Marshal(base64.EncodeToString(h.n))
		if err != nil {
			return nil, fmt.Errorf(`failed to marshal field %q: %w`, RSANKey, err)
		}
		pairs = append(pairs, fieldPair{Name: RSANKey, Value: v})
	}
	if h.x509CertChain != nil {
		v, err := json.Marshal(h.x509CertChain)
		if err != nil {
			return nil, fmt.Errorf(`failed to marshal field %q: %w`, X509CertChainKey, err)
		}
		pairs = append(pairs, fieldPair{Name: X509CertChainKey, Value: v})
	}
	if h.x509CertThumbprint != nil {
		v, err := json.Marshal(*(h.x509CertThumbprint))
		if err != nil {
			return nil, fmt.Errorf(`failed to marshal field %q: %w`, X509CertThumbprintKey, err)
		}
		pairs = append(pairs, fieldPair{Name: X509CertThumbprintKey, Value: v})
	}
	if h.x509CertThumbprintS256 != nil {
		v, err := json.Marshal(*(h.x509CertThumbprintS256))
		if err != nil {
			return nil, fmt.Errorf(`failed to marshal field %q: %w`, X509CertThumbprintS256Key, err)
		}
		pairs = append(pairs, fieldPair{Name: X509CertThumbprintS256Key, Value: v})
	}
	if h.x509URL != nil {
		v, err := json.Marshal(*(h.x509URL))
		if err != nil {
			return nil, fmt.Errorf(`failed to marshal field %q: %w`, X509URLKey, err)
		}
		pairs = append(pairs, fieldPair{Name: X509URLKey, Value: v})
	}
	for k, v := range h.privateParams {
		var encoded []byte
		switch v := v.(type) {
		case []byte:
			var err error
			encoded, err = json.Marshal(base64.EncodeToString(v))
			if err != nil {
				return nil, fmt.Errorf(`failed to marshal field %q: %w`, k, err)
			}
		default:
			var err error
			encoded, err = json.Marshal(v)
			if err != nil {
				return nil, fmt.Errorf(`failed to marshal field %q: %w`, k, err)
			}
		}
		pairs = append(pairs, fieldPair{Name: k, Value: encoded})
	}

	sort.Slice(pairs, func(i, j int) bool {
		return pairs[i].Name < pairs[j].Name
	})

	return pairs, nil
}

func (h *rsaPublicKey) MarshalJSON() ([]byte, error) {
	buf := pool.BytesBuffer().Get()
	defer pool.BytesBuffer().Put(buf)
	pairs, err := h.makePairs()
	if err != nil {
		return nil, fmt.Errorf(`failed to make pairs: %w`, err)
	}
	buf.WriteByte(tokens.OpenCurlyBracket)

	for i, pair := range pairs {
		if i > 0 {
			buf.WriteByte(tokens.Comma)
		}
		buf.WriteByte('"')
		buf.WriteString(pair.Name)
		buf.WriteString(`": `)
		buf.Write(pair.Value.([]byte))
	}
	buf.WriteByte(tokens.CloseCurlyBracket)
	ret := make([]byte, buf.Len())
	copy(ret, buf.Bytes())
	putFieldPairList(pairs)
	return ret, nil
}

func (h *rsaPublicKey) Keys() []string {
	h.mu.RLock()
	defer h.mu.RUnlock()
	keys := make([]string, 0, 10+len(h.privateParams))
	keys = append(keys, KeyTypeKey)
	if h.algorithm != nil {
		keys = append(keys, AlgorithmKey)
	}
	if h.e != nil {
		keys = append(keys, RSAEKey)
	}
	if h.keyID != nil {
		keys = append(keys, KeyIDKey)
	}
	if h.keyOps != nil {
		keys = append(keys, KeyOpsKey)
	}
	if h.keyUsage != nil {
		keys = append(keys, KeyUsageKey)
	}
	if h.n != nil {
		keys = append(keys, RSANKey)
	}
	if h.x509CertChain != nil {
		keys = append(keys, X509CertChainKey)
	}
	if h.x509CertThumbprint != nil {
		keys = append(keys, X509CertThumbprintKey)
	}
	if h.x509CertThumbprintS256 != nil {
		keys = append(keys, X509CertThumbprintS256Key)
	}
	if h.x509URL != nil {
		keys = append(keys, X509URLKey)
	}
	for k := range h.privateParams {
		keys = append(keys, k)
	}
	return keys
}

type RSAPrivateKey interface {
	Key
	D() ([]byte, bool)
	DP() ([]byte, bool)
	DQ() ([]byte, bool)
	E() ([]byte, bool)
	N() ([]byte, bool)
	P() ([]byte, bool)
	Q() ([]byte, bool)
	QI() ([]byte, bool)
}

type rsaPrivateKey struct {
	algorithm              *jwa.KeyAlgorithm // https://tools.ietf.org/html/rfc7517#section-4.4
	d                      []byte
	dp                     []byte
	dq                     []byte
	e                      []byte
	keyID                  *string           // https://tools.ietf.org/html/rfc7515#section-4.1.4
	keyOps                 *KeyOperationList // https://tools.ietf.org/html/rfc7517#section-4.3
	keyUsage               *string           // https://tools.ietf.org/html/rfc7517#section-4.2
	n                      []byte
	p                      []byte
	q                      []byte
	qi                     []byte
	x509CertChain          *cert.Chain // https://tools.ietf.org/html/rfc7515#section-4.1.6
	x509CertThumbprint     *string     // https://tools.ietf.org/html/rfc7515#section-4.1.7
	x509CertThumbprintS256 *string     // https://tools.ietf.org/html/rfc7515#section-4.1.8
	x509URL                *string     // https://tools.ietf.org/html/rfc7515#section-4.1.5
	privateParams          map[string]any
	mu                     sync.RWMutex
	dc                     json.DecodeCtx
}

var _ RSAPrivateKey = &rsaPrivateKey{}
var _ Key = &rsaPrivateKey{}

func newRSAPrivateKey() *rsaPrivateKey {
	return &rsaPrivateKey{
		privateParams: make(map[string]any),
	}
}

func (h *rsaPrivateKey) KeyType() jwa.KeyType {
	return jwa.RSA()
}

func (h *rsaPrivateKey) rlock() {
	h.mu.RLock()
}

func (h *rsaPrivateKey) runlock() {
	h.mu.RUnlock()
}

func (h *rsaPrivateKey) IsPrivate() bool {
	return true
}

func (h *rsaPrivateKey) Algorithm() (jwa.KeyAlgorithm, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	if h.algorithm != nil {
		return *(h.algorithm), true
	}
	return nil, false
}

func (h *rsaPrivateKey) D() ([]byte, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	if h.d != nil {
		return h.d, true
	}
	return nil, false
}

func (h *rsaPrivateKey) DP() ([]byte, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	if h.dp != nil {
		return h.dp, true
	}
	return nil, false
}

func (h *rsaPrivateKey) DQ() ([]byte, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	if h.dq != nil {
		return h.dq, true
	}
	return nil, false
}

func (h *rsaPrivateKey) E() ([]byte, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	if h.e != nil {
		return h.e, true
	}
	return nil, false
}

func (h *rsaPrivateKey) KeyID() (string, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	if h.keyID != nil {
		return *(h.keyID), true
	}
	return "", false
}

func (h *rsaPrivateKey) KeyOps() (KeyOperationList, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	if h.keyOps != nil {
		return *(h.keyOps), true
	}
	return nil, false
}

func (h *rsaPrivateKey) KeyUsage() (string, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	if h.keyUsage != nil {
		return *(h.keyUsage), true
	}
	return "", false
}

func (h *rsaPrivateKey) N() ([]byte, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	if h.n != nil {
		return h.n, true
	}
	return nil, false
}

func (h *rsaPrivateKey) P() ([]byte, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	if h.p != nil {
		return h.p, true
	}
	return nil, false
}

func (h *rsaPrivateKey) Q() ([]byte, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	if h.q != nil {
		return h.q, true
	}
	return nil, false
}

func (h *rsaPrivateKey) QI() ([]byte, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	if h.qi != nil {
		return h.qi, true
	}
	return nil, false
}

func (h *rsaPrivateKey) X509CertChain() (*cert.Chain, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	if h.x509CertChain != nil {
		return h.x509CertChain, true
	}
	return nil, false
}

func (h *rsaPrivateKey) X509CertThumbprint() (string, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	if h.x509CertThumbprint != nil {
		return *(h.x509CertThumbprint), true
	}
	return "", false
}

func (h *rsaPrivateKey) X509CertThumbprintS256() (string, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	if h.x509CertThumbprintS256 != nil {
		return *(h.x509CertThumbprintS256), true
	}
	return "", false
}

func (h *rsaPrivateKey) X509URL() (string, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	if h.x509URL != nil {
		return *(h.x509URL), true
	}
	return "", false
}

func (h *rsaPrivateKey) Has(name string) bool {
	h.mu.RLock()
	defer h.mu.RUnlock()
	switch name {
	case KeyTypeKey:
		return true
	case AlgorithmKey:
		return h.algorithm != nil
	case RSADKey:
		return h.d != nil
	case RSADPKey:
		return h.dp != nil
	case RSADQKey:
		return h.dq != nil
	case RSAEKey:
		return h.e != nil
	case KeyIDKey:
		return h.keyID != nil
	case KeyOpsKey:
		return h.keyOps != nil
	case KeyUsageKey:
		return h.keyUsage != nil
	case RSANKey:
		return h.n != nil
	case RSAPKey:
		return h.p != nil
	case RSAQKey:
		return h.q != nil
	case RSAQIKey:
		return h.qi != nil
	case X509CertChainKey:
		return h.x509CertChain != nil
	case X509CertThumbprintKey:
		return h.x509CertThumbprint != nil
	case X509CertThumbprintS256Key:
		return h.x509CertThumbprintS256 != nil
	case X509URLKey:
		return h.x509URL != nil
	default:
		_, ok := h.privateParams[name]
		return ok
	}
}

func (h *rsaPrivateKey) Get(name string, dst any) error {
	h.mu.RLock()
	defer h.mu.RUnlock()
	switch name {
	case KeyTypeKey:
		if err := blackmagic.AssignIfCompatible(dst, h.KeyType()); err != nil {
			return fmt.Errorf(`rsaPrivateKey.Get: failed to assign value for field %q to destination object: %w`, name, err)
		}
	case AlgorithmKey:
		if h.algorithm == nil {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, *(h.algorithm)); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
		return nil
	case RSADKey:
		if h.d == nil {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, h.d); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
		return nil
	case RSADPKey:
		if h.dp == nil {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, h.dp); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
		return nil
	case RSADQKey:
		if h.dq == nil {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, h.dq); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
		return nil
	case RSAEKey:
		if h.e == nil {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, h.e); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
		return nil
	case KeyIDKey:
		if h.keyID == nil {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, *(h.keyID)); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
		return nil
	case KeyOpsKey:
		if h.keyOps == nil {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, *(h.keyOps)); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
		return nil
	case KeyUsageKey:
		if h.keyUsage == nil {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, *(h.keyUsage)); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
		return nil
	case RSANKey:
		if h.n == nil {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, h.n); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
		return nil
	case RSAPKey:
		if h.p == nil {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, h.p); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
		return nil
	case RSAQKey:
		if h.q == nil {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, h.q); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
		return nil
	case RSAQIKey:
		if h.qi == nil {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, h.qi); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
		return nil
	case X509CertChainKey:
		if h.x509CertChain == nil {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, h.x509CertChain); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
		return nil
	case X509CertThumbprintKey:
		if h.x509CertThumbprint == nil {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, *(h.x509CertThumbprint)); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
		return nil
	case X509CertThumbprintS256Key:
		if h.x509CertThumbprintS256 == nil {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, *(h.x509CertThumbprintS256)); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
		return nil
	case X509URLKey:
		if h.x509URL == nil {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, *(h.x509URL)); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
		return nil
	default:
		v, ok := h.privateParams[name]
		if !ok {
			return fmt.Errorf(`field %q not found`, name)
		}
		if err := blackmagic.AssignIfCompatible(dst, v); err != nil {
			return fmt.Errorf(`failed to assign value for field %q: %w`, name, err)
		}
	}
	return nil
}

func (h *rsaPrivateKey) Set(name string, value any) error {
	h.mu.Lock()
	defer h.mu.Unlock()
	return h.setNoLock(name, value)
}

func (h *rsaPrivateKey) setNoLock(name string, value any) error {
	switch name {
	case "kty":
		return nil
	case AlgorithmKey:
		switch v := value.(type) {
		case string, jwa.SignatureAlgorithm, jwa.KeyEncryptionAlgorithm, jwa.ContentEncryptionAlgorithm:
			tmp, err := jwa.KeyAlgorithmFrom(v)
			if err != nil {
				return fmt.Errorf(`invalid algorithm for %q key: %w`, AlgorithmKey, err)
			}
			h.algorithm = &tmp
		default:
			return fmt.Errorf(`invalid type for %q key: %T`, AlgorithmKey, value)
		}
		return nil
	case RSADKey:
		if v, ok := value.([]byte); ok {
			if v == nil {
				h.d = nil
			} else {
				h.d = make([]byte, len(v))
				copy(h.d, v)
			}
			return nil
		}
		return fmt.Errorf(`invalid value for %s key: %T`, RSADKey, value)
	case RSADPKey:
		if v, ok := value.([]byte); ok {
			if v == nil {
				h.dp = nil
			} else {
				h.dp = make([]byte, len(v))
				copy(h.dp, v)
			}
			return nil
		}
		return fmt.Errorf(`invalid value for %s key: %T`, RSADPKey, value)
	case RSADQKey:
		if v, ok := value.([]byte); ok {
			if v == nil {
				h.dq = nil
			} else {
				h.dq = make([]byte, len(v))
				copy(h.dq, v)
			}
			return nil
		}
		return fmt.Errorf(`invalid value for %s key: %T`, RSADQKey, value)
	case RSAEKey:
		if v, ok := value.([]byte); ok {
			if v == nil {
				h.e = nil
			} else {
				h.e = make([]byte, len(v))
				copy(h.e, v)
			}
			return nil
		}
		return fmt.Errorf(`invalid value for %s key: %T`, RSAEKey, value)
	case KeyIDKey:
		if v, ok := value.(string); ok {
			h.keyID = &v
			return nil
		}
		return fmt.Errorf(`invalid value for %s key: %T`, KeyIDKey, value)
	case KeyOpsKey:
		var acceptor KeyOperationList
		if err := acceptor.Accept(value); err != nil {
			return fmt.Errorf(`invalid value for %s key: %w`, KeyOpsKey, err)
		}
		h.keyOps = &acceptor
		return nil
	case KeyUsageKey:
		switch v := value.(type) {
		case KeyUsageType:
			switch v {
			case ForSignature, ForEncryption:
				tmp := v.String()
				h.keyUsage = &tmp
			default:
				return fmt.Errorf(`invalid key usage type %s`, v)
			}
		case string:
			h.keyUsage = &v
		default:
			return fmt.Errorf(`invalid key usage type %s`, v)
		}
	case RSANKey:
		if v, ok := value.([]byte); ok {
			if v == nil {
				h.n = nil
			} else {
				h.n = make([]byte, len(v))
				copy(h.n, v)
			}
			return nil
		}
		return fmt.Errorf(`invalid value for %s key: %T`, RSANKey, value)
	case RSAPKey:
		if v, ok := value.([]byte); ok {
			if v == nil {
				h.p = nil
			} else {
				h.p = make([]byte, len(v))
				copy(h.p, v)
			}
			return nil
		}
		return fmt.Errorf(`invalid value for %s key: %T`, RSAPKey, value)
	case RSAQKey:
		if v, ok := value.([]byte); ok {
			if v == nil {
				h.q = nil
			} else {
				h.q = make([]byte, len(v))
				copy(h.q, v)
			}
			return nil
		}
		return fmt.Errorf(`invalid value for %s key: %T`, RSAQKey, value)
	case RSAQIKey:
		if v, ok := value.([]byte); ok {
			if v == nil {
				h.qi = nil
			} else {
				h.qi = make([]byte, len(v))
				copy(h.qi, v)
			}
			return nil
		}
		return fmt.Errorf(`invalid value for %s key: %T`, RSAQIKey, value)
	case X509CertChainKey:
		if v, ok := value.(*cert.Chain); ok {
			h.x509CertChain = v
			return nil
		}
		return fmt.Errorf(`invalid value for %s key: %T`, X509CertChainKey, value)
	case X509CertThumbprintKey:
		if v, ok := value.(string); ok {
			h.x509CertThumbprint = &v
			return nil
		}
		return fmt.Errorf(`invalid value for %s key: %T`, X509CertThumbprintKey, value)
	case X509CertThumbprintS256Key:
		if v, ok := value.(string); ok {
			h.x509CertThumbprintS256 = &v
			return nil
		}
		return fmt.Errorf(`invalid value for %s key: %T`, X509CertThumbprintS256Key, value)
	case X509URLKey:
		if v, ok := value.(string); ok {
			h.x509URL = &v
			return nil
		}
		return fmt.Errorf(`invalid value for %s key: %T`, X509URLKey, value)
	default:
		if h.privateParams == nil {
			h.privateParams = map[string]any{}
		}
		h.privateParams[name] = value
	}
	return nil
}

func (k *rsaPrivateKey) Remove(key string) error {
	k.mu.Lock()
	defer k.mu.Unlock()
	switch key {
	case AlgorithmKey:
		k.algorithm = nil
	case RSADKey:
		k.d = nil
	case RSADPKey:
		k.dp = nil
	case RSADQKey:
		k.dq = nil
	case RSAEKey:
		k.e = nil
	case KeyIDKey:
		k.keyID = nil
	case KeyOpsKey:
		k.keyOps = nil
	case KeyUsageKey:
		k.keyUsage = nil
	case RSANKey:
		k.n = nil
	case RSAPKey:
		k.p = nil
	case RSAQKey:
		k.q = nil
	case RSAQIKey:
		k.qi = nil
	case X509CertChainKey:
		k.x509CertChain = nil
	case X509CertThumbprintKey:
		k.x509CertThumbprint = nil
	case X509CertThumbprintS256Key:
		k.x509CertThumbprintS256 = nil
	case X509URLKey:
		k.x509URL = nil
	default:
		delete(k.privateParams, key)
	}
	return nil
}

func (k *rsaPrivateKey) Clone() (Key, error) {
	key, err := cloneKey(k)
	if err != nil {
		return nil, fmt.Errorf(`rsaPrivateKey.Clone: %w`, err)
	}
	return key, nil
}

func (k *rsaPrivateKey) DecodeCtx() json.DecodeCtx {
	k.mu.RLock()
	defer k.mu.RUnlock()
	return k.dc
}

func (k *rsaPrivateKey) SetDecodeCtx(dc json.DecodeCtx) {
	k.mu.Lock()
	defer k.mu.Unlock()
	k.dc = dc
}

func (h *rsaPrivateKey) UnmarshalJSON(buf []byte) (retErr error) {
	h.mu.Lock()
	defer h.mu.Unlock()
	h.algorithm = nil
	h.d = nil
	h.dp = nil
	h.dq = nil
	h.e = nil
	h.keyID = nil
	h.keyOps = nil
	h.keyUsage = nil
	h.n = nil
	h.p = nil
	h.q = nil
	h.qi = nil
	h.x509CertChain = nil
	h.x509CertThumbprint = nil
	h.x509CertThumbprintS256 = nil
	h.x509URL = nil
	defer func() {
		if retErr != nil {
			clear(h.d)
			h.d = nil
			clear(h.dp)
			h.dp = nil
			clear(h.dq)
			h.dq = nil
			clear(h.e)
			h.e = nil
			clear(h.n)
			h.n = nil
			clear(h.p)
			h.p = nil
			clear(h.q)
			h.q = nil
			clear(h.qi)
			h.qi = nil
		}
	}()
	dec := json.NewDecoder(bytes.NewReader(buf))
LOOP:
	for {
		tok, err := dec.Token()
		if err != nil {
			return fmt.Errorf(`error reading token: %w`, err)
		}
		switch tok := tok.(type) {
		case json.Delim:
			// Assuming we're doing everything correctly, we should ONLY
			// get either tokens.OpenCurlyBracket or tokens.CloseCurlyBracket here.
			if tok == tokens.CloseCurlyBracket { // End of object
				break LOOP
			} else if tok != tokens.OpenCurlyBracket {
				return fmt.Errorf(`expected '%c' but got '%c'`, tokens.OpenCurlyBracket, tok)
			}
		case string: // Objects can only have string keys
			switch tok {
			case KeyTypeKey:
				val, err := json.ReadNextStringToken(dec, h.dc)
				if err != nil {
					return fmt.Errorf(`error reading token: %w`, err)
				}
				if val != jwa.RSA().String() {
					return fmt.Errorf(`invalid kty value for RSAPublicKey (%s)`, val)
				}
			case AlgorithmKey:
				var s string
				if err := dec.Decode(&s); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, AlgorithmKey, err)
				}
				alg, err := jwa.KeyAlgorithmFrom(s)
				if err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, AlgorithmKey, err)
				}
				h.algorithm = &alg
			case RSADKey:
				if err := json.AssignNextBytesToken(&h.d, dec); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, RSADKey, err)
				}
			case RSADPKey:
				if err := json.AssignNextBytesToken(&h.dp, dec); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, RSADPKey, err)
				}
			case RSADQKey:
				if err := json.AssignNextBytesToken(&h.dq, dec); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, RSADQKey, err)
				}
			case RSAEKey:
				if err := json.AssignNextBytesToken(&h.e, dec); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, RSAEKey, err)
				}
			case KeyIDKey:
				if err := json.AssignNextStringToken(&h.keyID, dec, h.dc); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, KeyIDKey, err)
				}
			case KeyOpsKey:
				var decoded KeyOperationList
				if err := dec.Decode(&decoded); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, KeyOpsKey, err)
				}
				h.keyOps = &decoded
			case KeyUsageKey:
				if err := json.AssignNextStringToken(&h.keyUsage, dec, h.dc); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, KeyUsageKey, err)
				}
			case RSANKey:
				if err := json.AssignNextBytesToken(&h.n, dec); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, RSANKey, err)
				}
			case RSAPKey:
				if err := json.AssignNextBytesToken(&h.p, dec); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, RSAPKey, err)
				}
			case RSAQKey:
				if err := json.AssignNextBytesToken(&h.q, dec); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, RSAQKey, err)
				}
			case RSAQIKey:
				if err := json.AssignNextBytesToken(&h.qi, dec); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, RSAQIKey, err)
				}
			case X509CertChainKey:
				var decoded cert.Chain
				if err := dec.Decode(&decoded); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, X509CertChainKey, err)
				}
				h.x509CertChain = &decoded
			case X509CertThumbprintKey:
				if err := json.AssignNextStringToken(&h.x509CertThumbprint, dec, h.dc); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, X509CertThumbprintKey, err)
				}
			case X509CertThumbprintS256Key:
				if err := json.AssignNextStringToken(&h.x509CertThumbprintS256, dec, h.dc); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, X509CertThumbprintS256Key, err)
				}
			case X509URLKey:
				if err := json.AssignNextStringToken(&h.x509URL, dec, h.dc); err != nil {
					return fmt.Errorf(`failed to decode value for key %s: %w`, X509URLKey, err)
				}
			default:
				if dc := h.dc; dc != nil {
					if localReg := dc.Registry(); localReg != nil {
						decoded, err := localReg.Decode(dec, tok)
						if err == nil {
							h.setNoLock(tok, decoded)
							continue
						}
					}
				}
				decoded, err := fieldRegistry.Decode(dec, tok)
				if err == nil {
					h.setNoLock(tok, decoded)
					continue
				}
				return fmt.Errorf(`could not decode field %s: %w`, tok, err)
			}
		default:
			return fmt.Errorf(`invalid token %T`, tok)
		}
	}
	if h.d == nil {
		return fmt.Errorf(`required field d is missing`)
	}
	if h.e == nil {
		return fmt.Errorf(`required field e is missing`)
	}
	if h.n == nil {
		return fmt.Errorf(`required field n is missing`)
	}
	return nil
}

func (h *rsaPrivateKey) makePairs() ([]fieldPair, error) {
	pairs := getFieldPairList()
	h.mu.RLock()
	defer h.mu.RUnlock()
	{
		v, err := json.Marshal(jwa.RSA())
		if err != nil {
			return nil, fmt.Errorf(`failed to marshal field %q: %w`, KeyTypeKey, err)
		}
		pairs = append(pairs, fieldPair{Name: KeyTypeKey, Value: v})
	}
	if h.algorithm != nil {
		v, err := json.Marshal(*(h.algorithm))
		if err != nil {
			return nil, fmt.Errorf(`failed to marshal field %q: %w`, AlgorithmKey, err)
		}
		pairs = append(pairs, fieldPair{Name: AlgorithmKey, Value: v})
	}
	if h.d != nil {
		v, err := json.Marshal(base64.EncodeToString(h.d))
		if err != nil {
			return nil, fmt.Errorf(`failed to marshal field %q: %w`, RSADKey, err)
		}
		pairs = append(pairs, fieldPair{Name: RSADKey, Value: v})
	}
	if h.dp != nil {
		v, err := json.Marshal(base64.EncodeToString(h.dp))
		if err != nil {
			return nil, fmt.Errorf(`failed to marshal field %q: %w`, RSADPKey, err)
		}
		pairs = append(pairs, fieldPair{Name: RSADPKey, Value: v})
	}
	if h.dq != nil {
		v, err := json.Marshal(base64.EncodeToString(h.dq))
		if err != nil {
			return nil, fmt.Errorf(`failed to marshal field %q: %w`, RSADQKey, err)
		}
		pairs = append(pairs, fieldPair{Name: RSADQKey, Value: v})
	}
	if h.e != nil {
		v, err := json.Marshal(base64.EncodeToString(h.e))
		if err != nil {
			return nil, fmt.Errorf(`failed to marshal field %q: %w`, RSAEKey, err)
		}
		pairs = append(pairs, fieldPair{Name: RSAEKey, Value: v})
	}
	if h.keyID != nil {
		v, err := json.Marshal(*(h.keyID))
		if err != nil {
			return nil, fmt.Errorf(`failed to marshal field %q: %w`, KeyIDKey, err)
		}
		pairs = append(pairs, fieldPair{Name: KeyIDKey, Value: v})
	}
	if h.keyOps != nil {
		v, err := json.Marshal(*(h.keyOps))
		if err != nil {
			return nil, fmt.Errorf(`failed to marshal field %q: %w`, KeyOpsKey, err)
		}
		pairs = append(pairs, fieldPair{Name: KeyOpsKey, Value: v})
	}
	if h.keyUsage != nil {
		v, err := json.Marshal(*(h.keyUsage))
		if err != nil {
			return nil, fmt.Errorf(`failed to marshal field %q: %w`, KeyUsageKey, err)
		}
		pairs = append(pairs, fieldPair{Name: KeyUsageKey, Value: v})
	}
	if h.n != nil {
		v, err := json.Marshal(base64.EncodeToString(h.n))
		if err != nil {
			return nil, fmt.Errorf(`failed to marshal field %q: %w`, RSANKey, err)
		}
		pairs = append(pairs, fieldPair{Name: RSANKey, Value: v})
	}
	if h.p != nil {
		v, err := json.Marshal(base64.EncodeToString(h.p))
		if err != nil {
			return nil, fmt.Errorf(`failed to marshal field %q: %w`, RSAPKey, err)
		}
		pairs = append(pairs, fieldPair{Name: RSAPKey, Value: v})
	}
	if h.q != nil {
		v, err := json.Marshal(base64.EncodeToString(h.q))
		if err != nil {
			return nil, fmt.Errorf(`failed to marshal field %q: %w`, RSAQKey, err)
		}
		pairs = append(pairs, fieldPair{Name: RSAQKey, Value: v})
	}
	if h.qi != nil {
		v, err := json.Marshal(base64.EncodeToString(h.qi))
		if err != nil {
			return nil, fmt.Errorf(`failed to marshal field %q: %w`, RSAQIKey, err)
		}
		pairs = append(pairs, fieldPair{Name: RSAQIKey, Value: v})
	}
	if h.x509CertChain != nil {
		v, err := json.Marshal(h.x509CertChain)
		if err != nil {
			return nil, fmt.Errorf(`failed to marshal field %q: %w`, X509CertChainKey, err)
		}
		pairs = append(pairs, fieldPair{Name: X509CertChainKey, Value: v})
	}
	if h.x509CertThumbprint != nil {
		v, err := json.Marshal(*(h.x509CertThumbprint))
		if err != nil {
			return nil, fmt.Errorf(`failed to marshal field %q: %w`, X509CertThumbprintKey, err)
		}
		pairs = append(pairs, fieldPair{Name: X509CertThumbprintKey, Value: v})
	}
	if h.x509CertThumbprintS256 != nil {
		v, err := json.Marshal(*(h.x509CertThumbprintS256))
		if err != nil {
			return nil, fmt.Errorf(`failed to marshal field %q: %w`, X509CertThumbprintS256Key, err)
		}
		pairs = append(pairs, fieldPair{Name: X509CertThumbprintS256Key, Value: v})
	}
	if h.x509URL != nil {
		v, err := json.Marshal(*(h.x509URL))
		if err != nil {
			return nil, fmt.Errorf(`failed to marshal field %q: %w`, X509URLKey, err)
		}
		pairs = append(pairs, fieldPair{Name: X509URLKey, Value: v})
	}
	for k, v := range h.privateParams {
		var encoded []byte
		switch v := v.(type) {
		case []byte:
			var err error
			encoded, err = json.Marshal(base64.EncodeToString(v))
			if err != nil {
				return nil, fmt.Errorf(`failed to marshal field %q: %w`, k, err)
			}
		default:
			var err error
			encoded, err = json.Marshal(v)
			if err != nil {
				return nil, fmt.Errorf(`failed to marshal field %q: %w`, k, err)
			}
		}
		pairs = append(pairs, fieldPair{Name: k, Value: encoded})
	}

	sort.Slice(pairs, func(i, j int) bool {
		return pairs[i].Name < pairs[j].Name
	})

	return pairs, nil
}

func (h *rsaPrivateKey) MarshalJSON() ([]byte, error) {
	buf := pool.BytesBuffer().Get()
	defer pool.BytesBuffer().Put(buf)
	pairs, err := h.makePairs()
	if err != nil {
		return nil, fmt.Errorf(`failed to make pairs: %w`, err)
	}
	buf.WriteByte(tokens.OpenCurlyBracket)

	for i, pair := range pairs {
		if i > 0 {
			buf.WriteByte(tokens.Comma)
		}
		buf.WriteByte('"')
		buf.WriteString(pair.Name)
		buf.WriteString(`": `)
		buf.Write(pair.Value.([]byte))
	}
	buf.WriteByte(tokens.CloseCurlyBracket)
	ret := make([]byte, buf.Len())
	copy(ret, buf.Bytes())
	putFieldPairList(pairs)
	return ret, nil
}

func (h *rsaPrivateKey) Keys() []string {
	h.mu.RLock()
	defer h.mu.RUnlock()
	keys := make([]string, 0, 16+len(h.privateParams))
	keys = append(keys, KeyTypeKey)
	if h.algorithm != nil {
		keys = append(keys, AlgorithmKey)
	}
	if h.d != nil {
		keys = append(keys, RSADKey)
	}
	if h.dp != nil {
		keys = append(keys, RSADPKey)
	}
	if h.dq != nil {
		keys = append(keys, RSADQKey)
	}
	if h.e != nil {
		keys = append(keys, RSAEKey)
	}
	if h.keyID != nil {
		keys = append(keys, KeyIDKey)
	}
	if h.keyOps != nil {
		keys = append(keys, KeyOpsKey)
	}
	if h.keyUsage != nil {
		keys = append(keys, KeyUsageKey)
	}
	if h.n != nil {
		keys = append(keys, RSANKey)
	}
	if h.p != nil {
		keys = append(keys, RSAPKey)
	}
	if h.q != nil {
		keys = append(keys, RSAQKey)
	}
	if h.qi != nil {
		keys = append(keys, RSAQIKey)
	}
	if h.x509CertChain != nil {
		keys = append(keys, X509CertChainKey)
	}
	if h.x509CertThumbprint != nil {
		keys = append(keys, X509CertThumbprintKey)
	}
	if h.x509CertThumbprintS256 != nil {
		keys = append(keys, X509CertThumbprintS256Key)
	}
	if h.x509URL != nil {
		keys = append(keys, X509URLKey)
	}
	for k := range h.privateParams {
		keys = append(keys, k)
	}
	return keys
}

var rsaStandardFields KeyFilter

func init() {
	rsaStandardFields = NewFieldNameFilter(KeyTypeKey, KeyUsageKey, KeyOpsKey, AlgorithmKey, KeyIDKey, X509URLKey, X509CertChainKey, X509CertThumbprintKey, X509CertThumbprintS256Key, RSAEKey, RSANKey, RSADKey, RSADPKey, RSADQKey, RSAPKey, RSAQKey, RSAQIKey)
}

// RSAStandardFieldsFilter returns a KeyFilter that filters out standard RSA fields.
func RSAStandardFieldsFilter() KeyFilter {
	return rsaStandardFields
}

func init() {
	registry.Register(jwa.RSA().String(), registry.Constructor{
		Public:  func() any { return newRSAPublicKey() },
		Private: func() any { return newRSAPrivateKey() },
	})
}
