...

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

Documentation: github.com/MicahParks/keyfunc

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

View as plain text