// Determine the signature algorithm for a JWT.
333454
func signatureAlgorithm(jwk *jose.JSONWebKey) (alg jose.SignatureAlgorithm, err error) {
	if jwk.Key == nil {
		return alg, errors.New("no signing key")
	}
	switch key := jwk.Key.(type) {
	case *rsa.PrivateKey:
		// Because OIDC mandates that we support RS256, we always return that
		// value. In the future, we might want to make this configurable on a
		// per client basis. For example allowing PS256 or ECDSA variants.
		//
		// See https://github.com/dexidp/dex/issues/692
		return jose.RS256, nil
	case *ecdsa.PrivateKey:
		// We don't actually support ECDSA keys yet, but they're tested for
		// in case we want to in the future.
		//
		// These values are prescribed depending on the ECDSA key type. We
		// can't return different values.
		switch key.Params() {
		case elliptic.P256().Params():
			return jose.ES256, nil
		case elliptic.P384().Params():
			return jose.ES384, nil
		case elliptic.P521().Params():
			return jose.ES512, nil
		default:
			return alg, errors.New("unsupported ecdsa curve")
		}
	default:
		return alg, fmt.Errorf("unsupported signing key type %T", key)
	}
}
760779
func VerifySignature(msg []byte, sig *data.Signature, pk data.PublicKey) error {
	// method lookup is consistent due to Unmarshal JSON doing lower case for us.
	method := sig.Method
	verifier, ok := Verifiers[method]
	if !ok {
		return fmt.Errorf("signing method is not supported: %s", sig.Method)
	}

	if err := verifier.Verify(pk, sig.Signature, msg); err != nil {
		return fmt.Errorf("signature was invalid")
	}
	sig.IsValid = true
	return nil
}
480420
func (pk *PublicKey) VerifySignature(signed hash.Hash, sig *Signature) (err error) {
	if !pk.CanSign() {
		return errors.InvalidArgumentError("public key cannot generate signatures")
	}

	signed.Write(sig.HashSuffix)
	hashBytes := signed.Sum(nil)

	if hashBytes[0] != sig.HashTag[0] || hashBytes[1] != sig.HashTag[1] {
		return errors.SignatureError("hash tag doesn't match")
	}

	if pk.PubKeyAlgo != sig.PubKeyAlgo {
		return errors.InvalidArgumentError("public key and signature use different algorithms")
	}

	switch pk.PubKeyAlgo {
	case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly:
		rsaPublicKey, _ := pk.PublicKey.(*rsa.PublicKey)
		err = rsa.VerifyPKCS1v15(rsaPublicKey, sig.Hash, hashBytes, sig.RSASignature.bytes)
		if err != nil {
			return errors.SignatureError("RSA verification failure")
		}
		return nil
	case PubKeyAlgoDSA:
		dsaPublicKey, _ := pk.PublicKey.(*dsa.PublicKey)
		// Need to truncate hashBytes to match FIPS 186-3 section 4.6.
		subgroupSize := (dsaPublicKey.Q.BitLen() + 7) / 8
		if len(hashBytes) > subgroupSize {
			hashBytes = hashBytes[:subgroupSize]
		}
		if !dsa.Verify(dsaPublicKey, hashBytes, new(big.Int).SetBytes(sig.DSASigR.bytes), new(big.Int).SetBytes(sig.DSASigS.bytes)) {
			return errors.SignatureError("DSA verification failure")
		}
		return nil
	case PubKeyAlgoECDSA:
		ecdsaPublicKey := pk.PublicKey.(*ecdsa.PublicKey)
		if !ecdsa.Verify(ecdsaPublicKey, hashBytes, new(big.Int).SetBytes(sig.ECDSASigR.bytes), new(big.Int).SetBytes(sig.ECDSASigS.bytes)) {
			return errors.SignatureError("ECDSA verification failure")
		}
		return nil
	default:
		return errors.SignatureError("Unsupported public key algorithm used in signature")
	}
	panic("unreachable")
}
54625
func CalculateCertFingerprint(pemValue string) (string, error) {
	// The _ result below is not an error but the remaining PEM bytes.
	block, _ := pem.Decode([]byte(pemValue))
	if block == nil {
		return "", fmt.Errorf("no PEM-encoded data found")
	}

	if block.Type != "CERTIFICATE" {
		return "", fmt.Errorf("first PEM-block should be CERTIFICATE type")
	}

	hash := sha1.Sum(block.Bytes)
	return HexString(hash[:]), nil
}
137775
func GetSignature(auth *Auth, signing string) (string, error) {
	hashFunc := getHashFunction(auth.Algorithm)
	hash := hashFunc.New()
	hash.Write([]byte(signing))

	digest := hash.Sum(nil)

	signed, err := rsa.SignPKCS1v15(rand.Reader, auth.PrivateKey.key, hashFunc, digest)
	if err != nil {
		return "", fmt.Errorf("An error occurred while signing the key: %s", err)
	}

	return base64.StdEncoding.EncodeToString(signed), nil
}
213251
func (pk *PublicKey) VerifyRevocationSignature(sig *Signature) (err error) {
	h, err := keyRevocationHash(pk, sig.Hash)
	if err != nil {
		return err
	}
	return pk.VerifySignature(h, sig)
}
46752
func getSignature(signingKey []byte, stringToSign string) string {
	return hex.EncodeToString(sumHMAC(signingKey, []byte(stringToSign)))
}
606008
func getSignatureAlgorithm(tlsCert *tls.Certificate) (signatureAlgorithm, error) {
	privKey := tlsCert.PrivateKey
	switch privKey.(type) {
	case *rsa.PrivateKey:
		return rsaStringRepr, nil
	case *ecdsa.PrivateKey:
		return ecdsaStringRepr, nil
	default:
		return "", fmt.Errorf("Unsupported signature algorithm %T; RSA and ECDSA only are supported.", privKey)
	}
}
87709
func NewJWT(validity time.Duration, issuer string, s secrets.Secrets) (*JWTConfig, error) {

	if len(issuer) > MaxServerName {
		return nil, fmt.Errorf("server id should be max %d chars. got %s", MaxServerName, issuer)
	}

	for i := len(issuer); i < MaxServerName; i++ {
		issuer = issuer + " "
	}

	var signMethod jwt.SigningMethod
	compressionType := claimsheader.CompressionTypeNone

	if s == nil {
		return nil, errors.New("secrets can not be nil")
	}

	switch s.Type() {
	case secrets.PKICompactType:
		signMethod = jwt.SigningMethodES256
		compressionType = s.(*secrets.CompactPKI).Compressed
	default:
		signMethod = jwt.SigningMethodNone
	}

	return &JWTConfig{
		ValidityPeriod:       validity,
		Issuer:               issuer,
		signMethod:           signMethod,
		secrets:              s,
		tokenCache:           cache.NewCacheWithExpiration("JWTTokenCache", time.Millisecond*500),
		compressionType:      compressionType,
		compressionTagLength: claimsheader.CompressionTypeToTagLength(compressionType),
		datapathVersion:      claimsheader.DatapathVersion1,
	}, nil
}
207858
func ValidateAuthTokenWithReq(
	ctx types.Context,
	config *types.AuthConfig,
	req *http.Request) (*types.AuthToken, error) {

	return ValidateAuthTokenWithJWT(
		ctx, config, GetBearerTokenFromReq(ctx, req))
}
1198294
func VerifyWithJWK(buf []byte, key jwk.Key) (payload []byte, err error) {

	keyval, err := key.Materialize()
	if err != nil {
		return nil, errors.Wrap(err, `failed to materialize jwk.Key`)
	}

	payload, err = Verify(buf, jwa.SignatureAlgorithm(key.Algorithm()), keyval)
	if err != nil {
		return nil, errors.Wrap(err, "failed to verify message")
	}
	return payload, nil
}
362128
func Signature(params ...string) string {
	sort.Strings(params)
	h := sha1.New()
	for _, s := range params {
		io.WriteString(h, s)
	}
	return fmt.Sprintf("%x", h.Sum(nil))
}
1236989
func (idp *IDP) getChallengeToken(challengeString string) (*jwt.Token, error) {
	token, err := jwt.Parse(challengeString, func(token *jwt.Token) (interface{}, error) {
		_, ok := token.Method.(*jwt.SigningMethodRSA)
		if !ok {
			return nil, ErrorBadSigningMethod
		}

		return idp.getVerificationKey()
	})

	if err != nil {
		return nil, err
	}

	if !token.Valid {
		return nil, ErrorInvalidToken
	}

	return token, nil
}
857622
func VerifySignature(pubkey, msg, signature []byte) bool {
	if len(msg) != 32 || len(signature) != 64 || len(pubkey) == 0 {
		return false
	}
	sigdata := (*C.uchar)(unsafe.Pointer(&signature[0]))
	msgdata := (*C.uchar)(unsafe.Pointer(&msg[0]))
	keydata := (*C.uchar)(unsafe.Pointer(&pubkey[0]))
	return C.secp256k1_ext_ecdsa_verify(context, sigdata, msgdata, keydata, C.size_t(len(pubkey))) != 0
}
65002
func GetValidJWT(r *http.Request, publicKey *ecdsa.PublicKey) (token *jwt.Token, err error) {
	authorizationHeader := r.Header.Get("Authorization")
	if !strings.HasPrefix(authorizationHeader, "bearer ") && !strings.HasPrefix(authorizationHeader, "Bearer ") {
		return
	}
	jwtstring := strings.TrimSpace(strings.TrimPrefix(strings.TrimPrefix(authorizationHeader, "Bearer"), "bearer"))
	token, err = jwt.Parse(jwtstring, func(token *jwt.Token) (interface{}, error) {
		m, ok := token.Method.(*jwt.SigningMethodECDSA)
		if !ok {
			return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
		}
		if token.Header["alg"] != m.Alg() {
			return nil, fmt.Errorf("Unexpected signing algorithm: %v", token.Header["alg"])
		}
		return publicKey, nil
	})
	if err == nil && !token.Valid {
		err = errors.New("Invalid jwt supplied:" + jwtstring)
	}
	return
}
621046
func (s *SignerServer) Sign(ctx context.Context, sr *pb.SignatureRequest) (*pb.Signature, error) {
	privKey, _, err := findKeyByID(s.CryptoServices, sr.KeyID)

	logger := ctxu.GetLogger(ctx)

	switch err.(type) {
	case trustmanager.ErrKeyNotFound:
		logger.Errorf("Sign: key %s not found", sr.KeyID.ID)
		return nil, grpc.Errorf(codes.NotFound, err.Error())
	case nil:
		break
	default:
		logger.Errorf("Getting key %s failed: %s", sr.KeyID.ID, err.Error())
		return nil, grpc.Errorf(codes.Internal, err.Error())

	}

	sig, err := privKey.Sign(rand.Reader, sr.Content, nil)
	if err != nil {
		logger.Errorf("Sign: signing failed for KeyID %s on hash %s", sr.KeyID.ID, sr.Content)
		return nil, grpc.Errorf(codes.Internal, "Signing failed for KeyID %s on hash %s", sr.KeyID.ID, sr.Content)
	}

	logger.Info("Sign: Signed ", string(sr.Content), " with KeyID ", sr.KeyID.ID)

	signature := &pb.Signature{
		KeyInfo: &pb.KeyInfo{
			KeyID:     &pb.KeyID{ID: privKey.ID()},
			Algorithm: &pb.Algorithm{Algorithm: privKey.Algorithm()},
		},
		Algorithm: &pb.Algorithm{Algorithm: privKey.SignatureAlgorithm().String()},
		Content:   sig,
	}

	return signature, nil
}
1359637
func (pk *PublicKey) SerializeSignaturePrefix(h io.Writer) {
	var pLength uint16
	switch pk.PubKeyAlgo {
	case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly:
		pLength += 2 + uint16(len(pk.n.bytes))
		pLength += 2 + uint16(len(pk.e.bytes))
	case PubKeyAlgoDSA:
		pLength += 2 + uint16(len(pk.p.bytes))
		pLength += 2 + uint16(len(pk.q.bytes))
		pLength += 2 + uint16(len(pk.g.bytes))
		pLength += 2 + uint16(len(pk.y.bytes))
	case PubKeyAlgoElGamal:
		pLength += 2 + uint16(len(pk.p.bytes))
		pLength += 2 + uint16(len(pk.g.bytes))
		pLength += 2 + uint16(len(pk.y.bytes))
	case PubKeyAlgoECDSA:
		pLength += uint16(pk.ec.byteLen())
	case PubKeyAlgoECDH:
		pLength += uint16(pk.ec.byteLen())
		pLength += uint16(pk.ecdh.byteLen())
	default:
		panic("unknown public key algorithm")
	}
	pLength += 6
	h.Write([]byte{0x99, byte(pLength >> 8), byte(pLength)})
	return
}