/*
VerifyOAuth verifies the JWT token in the request using the public key configured
via CreateOAuth constructor.
*/
165004
func (a *oauth) VerifyOAuth(next http.Handler) httprouter.Handle {

	return func(rw http.ResponseWriter, r *http.Request, ps httprouter.Params) {

		/* Parse the JWT from the input request */
		jwt, err := jws.ParseJWTFromRequest(r)
		if err != nil {
			WriteErrorResponse(http.StatusBadRequest, err.Error(), rw)
			return
		}

		/* Get the pulic key from cache */
		pk := a.getPkSafe()
		if pk == nil {
			WriteErrorResponse(http.StatusBadRequest, "Public key not configured. Validation failed.", rw)
			return
		}

		/* Validate the token */
		err = jwt.Validate(pk, crypto.SigningMethodRS256)
		if err != nil {
			WriteErrorResponse(http.StatusBadRequest, err.Error(), rw)
			return
		}

		/* Set the input params in the request */
		r = SetParamsInRequest(r, ps)
		next.ServeHTTP(rw, r)
	}

}
303617
func (p *V1) Verify(token string, publicKey crypto.PublicKey, payload interface{}, footer interface{}) error {
	rsaPublicKey, ok := publicKey.(*rsa.PublicKey)
	if !ok {
		return ErrIncorrectPublicKeyType
	}

	data, footerBytes, err := splitToken([]byte(token), headerV1Public)
	if err != nil {
		return errors.Wrap(err, "failed to decode token")
	}

	if len(data) < v1SignSize {
		return errors.Wrap(ErrIncorrectTokenFormat, "incorrect signature size")
	}

	payloadBytes := data[:len(data)-v1SignSize]
	signature := data[len(data)-v1SignSize:]

	var opts rsa.PSSOptions
	opts.SaltLength = rsa.PSSSaltLengthEqualsHash
	PSSMessage := preAuthEncode(headerV1Public, payloadBytes, footerBytes)
	sha384 := crypto.SHA384
	pssHash := sha384.New()
	if _, err := pssHash.Write(PSSMessage); err != nil {
		return errors.Wrap(err, "failed to create pss hash")
	}
	hashed := pssHash.Sum(nil)

	if err = rsa.VerifyPSS(rsaPublicKey, sha384, hashed, signature, &opts); err != nil {
		return ErrInvalidSignature
	}

	if payload != nil {
		if err := fillValue(payloadBytes, payload); err != nil {
			return errors.Wrap(err, "failed to decode payload")
		}
	}

	if footer != nil {
		if err := fillValue(footerBytes, footer); err != nil {
			return errors.Wrap(err, "failed to decode footer")
		}
	}

	return nil
}
1265944
func (s *AccountService) VerifyCredentials(params *AccountVerifyParams) (*User, *http.Response, error) {
	user := new(User)
	apiError := new(APIError)
	resp, err := s.sling.New().Get("verify_credentials.json").QueryStruct(params).Receive(user, apiError)
	return user, resp, relevantError(err, *apiError)
}
163458
func (*SignatureScheme) Verify(ipk handlers.IssuerPublicKey, signature, digest []byte, attributes []bccsp.IdemixAttribute, rhIndex int, revocationPublicKey *ecdsa.PublicKey, epoch int) (err error) {
	defer func() {
		if r := recover(); r != nil {
			err = errors.Errorf("failure [%s]", r)
		}
	}()

	iipk, ok := ipk.(*IssuerPublicKey)
	if !ok {
		return errors.Errorf("invalid issuer public key, expected *IssuerPublicKey, got [%T]", ipk)
	}

	sig := &cryptolib.Signature{}
	err = proto.Unmarshal(signature, sig)
	if err != nil {
		return err
	}

	disclosure := make([]byte, len(attributes))
	attrValues := make([]*FP256BN.BIG, len(attributes))
	for i := 0; i < len(attributes); i++ {
		switch attributes[i].Type {
		case bccsp.IdemixHiddenAttribute:
			disclosure[i] = 0
			attrValues[i] = nil
		case bccsp.IdemixBytesAttribute:
			disclosure[i] = 1
			attrValues[i] = cryptolib.HashModOrder(attributes[i].Value.([]byte))
		case bccsp.IdemixIntAttribute:
			disclosure[i] = 1
			attrValues[i] = FP256BN.NewBIGint(attributes[i].Value.(int))
		default:
			err = errors.Errorf("attribute type not allowed or supported [%v] at position [%d]", attributes[i].Type, i)
		}
	}
	if err != nil {
		return
	}

	return sig.Ver(
		disclosure,
		iipk.PK,
		digest,
		attrValues,
		rhIndex,
		revocationPublicKey,
		epoch)
}
1308295
func Verify(sig []byte, publicKey PublicKey) bool {
	if l := len(publicKey); l != PublicKeySize {
		panic("sign: bad public key length: " + strconv.Itoa(l))
	}

	if len(sig) < SignatureSize || sig[63]&224 != 0 {
		return false
	}
	msg := sig[SignatureSize:]
	sig = sig[:SignatureSize]

	return ed25519.Verify(ed25519.PublicKey(publicKey), msg, sig)
}
228702
func (m *Module) Verify(state, token string) (bool, error) {
	obj, err := jose.ParseEncrypted(token)
	if err != nil {
		return false, errors.Wrap(err)
	}
	b, err := obj.Decrypt(m.decryptionKey)
	csrfPayload := &csrfPayload{}
	if err = json.Unmarshal(b, csrfPayload); err != nil {
		return false, errors.Wrap(err)
	}
	if state != csrfPayload.State {
		return false, nil
	}
	if time.Now().After(csrfPayload.ExpireAfter) {
		return false, nil
	}
	return true, nil
}
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
}
962930
func (k SigningPublicKey) Verify(msg []byte, sig []byte) error {
	ok := ed25519.Verify(k[:], msg, sig)
	if !ok {
		return saltpack.ErrBadSignature
	}
	return nil
}
67406
func (m *signingMethodNone) Verify(signingString, signature string, key interface{}) (err error) {
	// Key must be UnsafeAllowNoneSignatureType to prevent accidentally
	// accepting 'none' signing method
	if _, ok := key.(unsafeNoneMagicConstant); !ok {
		return NoneSignatureTypeDisallowedError
	}
	// If signing method is none, signature must be an empty string
	if signature != "" {
		return NewValidationError(
			"'none' signing method with non-empty signature",
			ValidationErrorSignatureInvalid,
		)
	}

	// Accept 'none' signing method.
	return nil
}
448928
func builtinJWTVerifyHS256(a ast.Value, b ast.Value) (ast.Value, error) {
	// Decode the JSON Web Token
	token, err := decodeJWT(a)
	if err != nil {
		return nil, err
	}

	// Process Secret input
	astSecret, err := builtins.StringOperand(b, 2)
	if err != nil {
		return nil, err
	}
	secret := string(astSecret)

	mac := hmac.New(sha256.New, []byte(secret))
	_, err = mac.Write([]byte(token.header + "." + token.payload))
	if err != nil {
		return nil, err
	}

	signature, err := token.decodeSignature()
	if err != nil {
		return nil, err
	}

	return ast.Boolean(hmac.Equal([]byte(signature), mac.Sum(nil))), nil
}
1038768
func builtinJWTVerifyRS256(a ast.Value, b ast.Value) (ast.Value, error) {
	return builtinJWTVerifyRSA(a, b, func(publicKey *rsa.PublicKey, digest []byte, signature []byte) error {
		return rsa.VerifyPKCS1v15(
			publicKey,
			crypto.SHA256,
			digest,
			signature)
	})
}
517762
func (v Ed25519Verifier) Verify(key data.PublicKey, sig []byte, msg []byte) error {
	if key.Algorithm() != data.ED25519Key {
		return ErrInvalidKeyType{}
	}
	sigBytes := make([]byte, ed25519.SignatureSize)
	if len(sig) != ed25519.SignatureSize {
		logrus.Debugf("signature length is incorrect, must be %d, was %d.", ed25519.SignatureSize, len(sig))
		return ErrInvalid
	}
	copy(sigBytes, sig)

	keyBytes := make([]byte, ed25519.PublicKeySize)
	pub := key.Public()
	if len(pub) != ed25519.PublicKeySize {
		logrus.Errorf("public key is incorrect size, must be %d, was %d.", ed25519.PublicKeySize, len(pub))
		return ErrInvalidKeyLength{msg: fmt.Sprintf("ed25519 public key must be %d bytes.", ed25519.PublicKeySize)}
	}
	n := copy(keyBytes, key.Public())
	if n < ed25519.PublicKeySize {
		logrus.Errorf("failed to copy the key, must have %d bytes, copied %d bytes.", ed25519.PublicKeySize, n)
		return ErrInvalid
	}

	if !ed25519.Verify(ed25519.PublicKey(keyBytes), msg, sigBytes) {
		logrus.Debugf("failed ed25519 verification")
		return ErrInvalid
	}
	return nil
}
488630
func (p *tokenManager) Verify(token []byte) (*DatapathKey, error) {

	tokenString := string(token)
	if pk, err := p.keycache.Get(tokenString); err == nil {
		return pk.(*DatapathKey), err
	}

	claims := &verifierClaims{}
	var JWTToken *jwt.Token
	var err error
	for _, pk := range p.publicKeys {

		if pk == nil {
			continue
		}

		JWTToken, err = jwt.ParseWithClaims(tokenString, claims, func(_ *jwt.Token) (interface{}, error) { // nolint
			return pk, nil
		})
		if err != nil || !JWTToken.Valid {
			continue
		}

		dp := &DatapathKey{
			PublicKey: KeyFromClaims(claims),
			Tags:      claims.Tags,
		}

		if time.Now().Add(p.validity).Unix() <= claims.ExpiresAt {
			p.keycache.AddOrUpdate(tokenString, dp)
		}
		return dp, nil
	}

	return nil, errors.New("unable to verify token against any available public key")
}
670428
func (s *Signatory) verifySignature(block *clearsign.Block) (*openpgp.Entity, error) {
	return openpgp.CheckDetachedSignature(
		s.KeyRing,
		bytes.NewBuffer(block.Bytes),
		block.ArmoredSignature.Body,
	)
}
993410
func (ya *YubiAuth) HttpsVerifyCertificate(verifyCertificate bool) {
	// Lock
	ya.use.Lock()
	defer ya.use.Unlock()

	// save setting
	ya.verifyCertificate = verifyCertificate

	// rebuild workers (client has to be changed)
	ya.buildWorkers()
}
727645
func (js *JSONSignature) Verify() ([]PublicKey, error) {
	keys := make([]PublicKey, len(js.signatures))
	for i, signature := range js.signatures {
		signBytes, err := js.signBytes(signature.Protected)
		if err != nil {
			return nil, err
		}
		var publicKey PublicKey
		if len(signature.Header.Chain) > 0 {
			certBytes, err := base64.StdEncoding.DecodeString(signature.Header.Chain[0])
			if err != nil {
				return nil, err
			}
			cert, err := x509.ParseCertificate(certBytes)
			if err != nil {
				return nil, err
			}
			publicKey, err = FromCryptoPublicKey(cert.PublicKey)
			if err != nil {
				return nil, err
			}
		} else if signature.Header.JWK != nil {
			publicKey = signature.Header.JWK
		} else {
			return nil, errors.New("missing public key")
		}

		sigBytes, err := joseBase64UrlDecode(signature.Signature)
		if err != nil {
			return nil, err
		}

		err = publicKey.Verify(bytes.NewReader(signBytes), signature.Header.Algorithm, sigBytes)
		if err != nil {
			return nil, err
		}

		keys[i] = publicKey
	}
	return keys, nil
}
907611
func (j *JwtAuthenticator) AuthenticateToken(ctx context.Context, rawtoken string) (*Claims, error) {

	// Parse token
	token, err := jwt.Parse(rawtoken, func(token *jwt.Token) (interface{}, error) {

		// Verify Method
		if strings.HasPrefix(token.Method.Alg(), "RS") {
			// RS256, RS384, or RS512
			return j.rsaKey, nil
		} else if strings.HasPrefix(token.Method.Alg(), "ES") {
			// ES256, ES384, or ES512
			return j.ecdsKey, nil
		} else if strings.HasPrefix(token.Method.Alg(), "HS") {
			// HS256, HS384, or HS512
			return j.sharedSecretKey, nil
		}
		return nil, fmt.Errorf("Unknown token algorithm: %s", token.Method.Alg())
	})
	if err != nil {
		return nil, err
	}

	if !token.Valid {
		return nil, fmt.Errorf("Token failed validation")
	}

	// Get claims
	claims, ok := token.Claims.(jwt.MapClaims)
	if claims == nil || !ok {
		return nil, fmt.Errorf("No claims found in token")
	}

	// Check for required claims
	for _, requiredClaim := range requiredClaims {
		if _, ok := claims[requiredClaim]; !ok {
			// Claim missing
			return nil, fmt.Errorf("Required claim %v missing from token", requiredClaim)
		}
	}

	// Token now has been verified.
	// Claims holds all the authorization information.
	// Here we need to first decode it then unmarshal it from JSON
	parts := strings.Split(token.Raw, ".")
	claimBytes, err := jwt.DecodeSegment(parts[1])
	if err != nil {
		return nil, fmt.Errorf("Failed to decode claims: %v", err)
	}
	var sdkClaims Claims
	err = json.Unmarshal(claimBytes, &sdkClaims)
	if err != nil {
		return nil, fmt.Errorf("Unable to get sdkclaims: %v", err)
	}

	if err := validateUsername(j.usernameClaim, &sdkClaims); err != nil {
		return nil, err
	}

	return &sdkClaims, nil
}