...

Source file src/github.com/MicahParks/keyfunc/v2/ecdsa.go

Documentation: github.com/MicahParks/keyfunc/v2

     1  package keyfunc
     2  
     3  import (
     4  	"crypto/ecdsa"
     5  	"crypto/elliptic"
     6  	"errors"
     7  	"fmt"
     8  	"math/big"
     9  )
    10  
    11  const (
    12  	// ktyEC is the key type (kty) in the JWT header for ECDSA.
    13  	ktyEC = "EC"
    14  
    15  	// p256 represents a 256-bit cryptographic elliptical curve type.
    16  	p256 = "P-256"
    17  
    18  	// p384 represents a 384-bit cryptographic elliptical curve type.
    19  	p384 = "P-384"
    20  
    21  	// p521 represents a 521-bit cryptographic elliptical curve type.
    22  	p521 = "P-521"
    23  )
    24  
    25  var (
    26  	// ErrECDSACurve indicates an error with the ECDSA curve.
    27  	ErrECDSACurve = errors.New("invalid ECDSA curve")
    28  )
    29  
    30  // ECDSA parses a jsonWebKey and turns it into an ECDSA public key.
    31  func (j *jsonWebKey) ECDSA() (publicKey *ecdsa.PublicKey, err error) {
    32  	if j.X == "" || j.Y == "" || j.Curve == "" {
    33  		return nil, fmt.Errorf("%w: %s", ErrMissingAssets, ktyEC)
    34  	}
    35  
    36  	// Decode the X coordinate from Base64.
    37  	//
    38  	// According to RFC 7518, this is a Base64 URL unsigned integer.
    39  	// https://tools.ietf.org/html/rfc7518#section-6.3
    40  	xCoordinate, err := base64urlTrailingPadding(j.X)
    41  	if err != nil {
    42  		return nil, err
    43  	}
    44  	yCoordinate, err := base64urlTrailingPadding(j.Y)
    45  	if err != nil {
    46  		return nil, err
    47  	}
    48  
    49  	publicKey = &ecdsa.PublicKey{}
    50  	switch j.Curve {
    51  	case p256:
    52  		publicKey.Curve = elliptic.P256()
    53  	case p384:
    54  		publicKey.Curve = elliptic.P384()
    55  	case p521:
    56  		publicKey.Curve = elliptic.P521()
    57  	default:
    58  		return nil, fmt.Errorf("%w: unknown curve: %s", ErrECDSACurve, j.Curve)
    59  	}
    60  
    61  	// Turn the X coordinate into *big.Int.
    62  	//
    63  	// According to RFC 7517, these numbers are in big-endian format.
    64  	// https://tools.ietf.org/html/rfc7517#appendix-A.1
    65  	publicKey.X = big.NewInt(0).SetBytes(xCoordinate)
    66  	publicKey.Y = big.NewInt(0).SetBytes(yCoordinate)
    67  
    68  	return publicKey, nil
    69  }
    70  

View as plain text