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

     1  package jwk
     2  
     3  import (
     4  	"crypto"
     5  	"fmt"
     6  
     7  	"github.com/lestrrat-go/blackmagic"
     8  	"github.com/lestrrat-go/jwx/v2/internal/base64"
     9  )
    10  
    11  func (k *symmetricKey) FromRaw(rawKey []byte) error {
    12  	k.mu.Lock()
    13  	defer k.mu.Unlock()
    14  
    15  	if len(rawKey) == 0 {
    16  		return fmt.Errorf(`non-empty []byte key required`)
    17  	}
    18  
    19  	k.octets = rawKey
    20  
    21  	return nil
    22  }
    23  
    24  // Raw returns the octets for this symmetric key.
    25  // Since this is a symmetric key, this just calls Octets
    26  func (k *symmetricKey) Raw(v interface{}) error {
    27  	k.mu.RLock()
    28  	defer k.mu.RUnlock()
    29  	return blackmagic.AssignIfCompatible(v, k.octets)
    30  }
    31  
    32  // Thumbprint returns the JWK thumbprint using the indicated
    33  // hashing algorithm, according to RFC 7638
    34  func (k *symmetricKey) Thumbprint(hash crypto.Hash) ([]byte, error) {
    35  	k.mu.RLock()
    36  	defer k.mu.RUnlock()
    37  	var octets []byte
    38  	if err := k.Raw(&octets); err != nil {
    39  		return nil, fmt.Errorf(`failed to materialize symmetric key: %w`, err)
    40  	}
    41  
    42  	h := hash.New()
    43  	fmt.Fprint(h, `{"k":"`)
    44  	fmt.Fprint(h, base64.EncodeToString(octets))
    45  	fmt.Fprint(h, `","kty":"oct"}`)
    46  	return h.Sum(nil), nil
    47  }
    48  
    49  func (k *symmetricKey) PublicKey() (Key, error) {
    50  	newKey := newSymmetricKey()
    51  
    52  	for _, pair := range k.makePairs() {
    53  		//nolint:forcetypeassert
    54  		key := pair.Key.(string)
    55  		if err := newKey.Set(key, pair.Value); err != nil {
    56  			return nil, fmt.Errorf(`failed to set field %q: %w`, key, err)
    57  		}
    58  	}
    59  	return newKey, nil
    60  }
    61  
    62  func (k *symmetricKey) Validate() error {
    63  	if len(k.Octets()) == 0 {
    64  		return NewKeyValidationError(fmt.Errorf(`jwk.SymmetricKey: missing "k" field`))
    65  	}
    66  	return nil
    67  }