// VerifyChains verifies all the signatures and the chains associated
// with each signature and returns the list of verified chains.
// Signatures without an x509 chain are not checked.
962659
func (js *JSONSignature) VerifyChains(ca *x509.CertPool) ([][]*x509.Certificate, error) {
	chains := make([][]*x509.Certificate, 0, len(js.signatures))
	for _, 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
			}
			intermediates := x509.NewCertPool()
			if len(signature.Header.Chain) > 1 {
				intermediateChain := signature.Header.Chain[1:]
				for i := range intermediateChain {
					certBytes, err := base64.StdEncoding.DecodeString(intermediateChain[i])
					if err != nil {
						return nil, err
					}
					intermediate, err := x509.ParseCertificate(certBytes)
					if err != nil {
						return nil, err
					}
					intermediates.AddCert(intermediate)
				}
			}

			verifyOptions := x509.VerifyOptions{
				Intermediates: intermediates,
				Roots:         ca,
			}

			verifiedChains, err := cert.Verify(verifyOptions)
			if err != nil {
				return nil, err
			}
			chains = append(chains, verifiedChains...)

			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
			}
		}

	}
	return chains, nil
}
1358719
func Verify(sum *[TagSize]byte, msg []byte, key *[16]byte) bool {
	var out [TagSize]byte
	Sum(&out, msg, key)
	return subtle.ConstantTimeCompare(sum[:], out[:]) == 1
}
770599
func (m *SigningMethodRSAPSS) Verify(signingString, signature string, key interface{}) error {
	var err error

	// Decode the signature
	var sig []byte
	if sig, err = DecodeSegment(signature); err != nil {
		return err
	}

	var rsaKey *rsa.PublicKey
	switch k := key.(type) {
	case *rsa.PublicKey:
		rsaKey = k
	default:
		return ErrInvalidKey
	}

	// Create hasher
	if !m.Hash.Available() {
		return ErrHashUnavailable
	}
	hasher := m.Hash.New()
	hasher.Write([]byte(signingString))

	return rsa.VerifyPSS(rsaKey, m.Hash, hasher.Sum(nil), sig, m.Options)
}
1265842
func VerifyPeerCertificate(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
	for _, chaincert := range rawCerts {
		cert, err := utils.DERToX509Certificate(chaincert)
		if err != nil {
			logger.Warn("Got error while verifying cert")
		}
		if cert != nil {
			err = ValidateCertificateDates(cert)
			if err != nil {
				//cert is expired or not valid
				logger.Warn(err.Error())
				return err
			}
		}
	}
	for _, certs := range verifiedChains {
		for _, cert := range certs {
			err := ValidateCertificateDates(cert)
			if err != nil {
				//cert is expired or not valid
				logger.Warn(err.Error())
				return err
			}
		}
	}
	return nil
}
984138
func (js *JSONSignature) SignWithChain(key PrivateKey, chain []*x509.Certificate) error {
	// Ensure key.Chain[0] is public key for key
	//key.Chain.PublicKey
	//key.PublicKey().CryptoPublicKey()

	// Verify chain
	protected, err := js.protectedHeader()
	if err != nil {
		return err
	}
	signBytes, err := js.signBytes(protected)
	if err != nil {
		return err
	}
	sigBytes, algorithm, err := key.Sign(bytes.NewReader(signBytes), crypto.SHA256)
	if err != nil {
		return err
	}

	header := jsHeader{
		Chain:     make([]string, len(chain)),
		Algorithm: algorithm,
	}

	for i, cert := range chain {
		header.Chain[i] = base64.StdEncoding.EncodeToString(cert.Raw)
	}

	js.signatures = append(js.signatures, jsSignature{
		Header:    header,
		Signature: joseBase64UrlEncode(sigBytes),
		Protected: protected,
	})

	return nil
}
1221210
func (csp *impl) Verify(k bccsp.Key, signature, digest []byte, opts bccsp.SignerOpts) (bool, error) {
	// Validate arguments
	if k == nil {
		return false, errors.New("Invalid Key. It must not be nil")
	}
	if len(signature) == 0 {
		return false, errors.New("Invalid signature. Cannot be empty")
	}
	if len(digest) == 0 {
		return false, errors.New("Invalid digest. Cannot be empty")
	}

	// Check key type
	switch k.(type) {
	case *ecdsaPrivateKey:
		return csp.verifyECDSA(k.(*ecdsaPrivateKey).pub, signature, digest, opts)
	case *ecdsaPublicKey:
		return csp.verifyECDSA(*k.(*ecdsaPublicKey), signature, digest, opts)
	default:
		return csp.BCCSP.Verify(k, signature, digest, opts)
	}
}
142464
func (v RSAPSSVerifier) Verify(key data.PublicKey, sig []byte, msg []byte) error {
	// will return err if keytype is not a recognized RSA type
	pubKey, err := getRSAPubKey(key)
	if err != nil {
		return err
	}

	digest := sha256.Sum256(msg)

	return verifyPSS(pubKey, digest[:], sig)
}
624286
func (b *Bundler) VerifyOptions() x509.VerifyOptions {
	return x509.VerifyOptions{
		Roots:         b.RootPool,
		Intermediates: b.IntermediatePool,
		KeyUsages:     b.opts.keyUsages,
	}
}
1196630
func (m *MockCryptoSuite) Verify(k core.Key, signature, digest []byte, opts core.SignerOpts) (valid bool, err error) {
	return true, nil
}
981186
func (*V2) Verify(token string, publicKey crypto.PublicKey, payload interface{}, footer interface{}) error {
	pub, ok := publicKey.(ed25519.PublicKey)
	if !ok {
		return ErrIncorrectPublicKeyType
	}

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

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

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

	if !ed25519.Verify(pub, preAuthEncode(headerV2Public, payloadBytes, footerBytes), signature) {
		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
}
1197577
func (s *MSPMessageCryptoService) VerifyBlock(chainID common.ChainID, seqNum uint64, signedBlock []byte) error {
	// - Convert signedBlock to common.Block.
	block, err := utils.GetBlockFromBlockBytes(signedBlock)
	if err != nil {
		return fmt.Errorf("Failed unmarshalling block bytes on channel [%s]: [%s]", chainID, err)
	}

	if block.Header == nil {
		return fmt.Errorf("Invalid Block on channel [%s]. Header must be different from nil.", chainID)
	}

	blockSeqNum := block.Header.Number
	if seqNum != blockSeqNum {
		return fmt.Errorf("Claimed seqNum is [%d] but actual seqNum inside block is [%d]", seqNum, blockSeqNum)
	}

	// - Extract channelID and compare with chainID
	channelID, err := utils.GetChainIDFromBlock(block)
	if err != nil {
		return fmt.Errorf("Failed getting channel id from block with id [%d] on channel [%s]: [%s]", block.Header.Number, chainID, err)
	}

	if channelID != string(chainID) {
		return fmt.Errorf("Invalid block's channel id. Expected [%s]. Given [%s]", chainID, channelID)
	}

	// - Unmarshal medatada
	if block.Metadata == nil || len(block.Metadata.Metadata) == 0 {
		return fmt.Errorf("Block with id [%d] on channel [%s] does not have metadata. Block not valid.", block.Header.Number, chainID)
	}

	metadata, err := utils.GetMetadataFromBlock(block, pcommon.BlockMetadataIndex_SIGNATURES)
	if err != nil {
		return fmt.Errorf("Failed unmarshalling medatata for signatures [%s]", err)
	}

	// - Verify that Header.DataHash is equal to the hash of block.Data
	// This is to ensure that the header is consistent with the data carried by this block
	if !bytes.Equal(block.Data.Hash(), block.Header.DataHash) {
		return fmt.Errorf("Header.DataHash is different from Hash(block.Data) for block with id [%d] on channel [%s]", block.Header.Number, chainID)
	}

	// - Get Policy for block validation

	// Get the policy manager for channelID
	cpm, ok := s.channelPolicyManagerGetter.Manager(channelID)
	if cpm == nil {
		return fmt.Errorf("Could not acquire policy manager for channel %s", channelID)
	}
	// ok is true if it was the manager requested, or false if it is the default manager
	mcsLogger.Debugf("Got policy manager for channel [%s] with flag [%t]", channelID, ok)

	// Get block validation policy
	policy, ok := cpm.GetPolicy(policies.BlockValidation)
	// ok is true if it was the policy requested, or false if it is the default policy
	mcsLogger.Debugf("Got block validation policy for channel [%s] with flag [%t]", channelID, ok)

	// - Prepare SignedData
	signatureSet := []*pcommon.SignedData{}
	for _, metadataSignature := range metadata.Signatures {
		shdr, err := utils.GetSignatureHeader(metadataSignature.SignatureHeader)
		if err != nil {
			return fmt.Errorf("Failed unmarshalling signature header for block with id [%d] on channel [%s]: [%s]", block.Header.Number, chainID, err)
		}
		signatureSet = append(
			signatureSet,
			&pcommon.SignedData{
				Identity:  shdr.Creator,
				Data:      util.ConcatenateBytes(metadata.Value, metadataSignature.SignatureHeader, block.Header.Bytes()),
				Signature: metadataSignature.Signature,
			},
		)
	}

	// - Evaluate policy
	return policy.Evaluate(signatureSet)
}
465881
func (c *Certificate) Verify(data []byte, sig *Signature) error {
	return c.Key.Verify(data, sig)
}
958955
func (k *JSONWebKeySet) VerifyJWT(jwt string) (body []byte, err error) {
	chunks := strings.Split(jwt, ".")
	if len(chunks) != 3 {
		return nil, fmt.Errorf("bad JWT - expected 3 components separated by '.'")
	}

	// Check the header, grab the corresponding public key.
	var hdr struct {
		Alg string `json:"alg"`
		Kid string `json:"kid"`
	}
	if err := unmarshalB64JSON(chunks[0], &hdr); err != nil {
		return nil, fmt.Errorf("bad JWT header - %s", err)
	}
	if hdr.Alg != "RS256" {
		return nil, fmt.Errorf("bad JWT - only RS256 alg is supported, not %q", hdr.Alg)
	}
	if hdr.Kid == "" {
		return nil, fmt.Errorf("bad JWT - missing the signing key ID in the header")
	}
	pub, ok := k.keys[hdr.Kid]
	if !ok {
		return nil, fmt.Errorf("can't verify JWT - unknown signing key %q", hdr.Kid)
	}

	// Decode the signature.
	sig, err := base64.RawURLEncoding.DecodeString(chunks[2])
	if err != nil {
		return nil, fmt.Errorf("bad JWT - can't base64 decode the signature - %s", err)
	}

	// Check the signature. The signed string is "b64(header).b64(body)".
	hasher := sha256.New()
	hasher.Write([]byte(chunks[0]))
	hasher.Write([]byte{'.'})
	hasher.Write([]byte(chunks[1]))
	if err := rsa.VerifyPKCS1v15(&pub, crypto.SHA256, hasher.Sum(nil), sig); err != nil {
		return nil, fmt.Errorf("bad JWT - bad signature")
	}

	// Decode the body. There should be no errors here generally, the encoded body
	// is signed and the signature was already verified.
	body, err = base64.RawURLEncoding.DecodeString(chunks[1])
	if err != nil {
		return nil, fmt.Errorf("bad JWT - can't base64 decode the body - %s", err)
	}
	return body, nil
}
982184
func (c *Client) VerifyChainLevelAsync(checkLevel int32) FutureVerifyChainResult {
	cmd := btcjson.NewVerifyChainCmd(&checkLevel, nil)
	return c.sendCmd(cmd)
}
1226795
func VerifyBlockSignature(block *common.Block, verifier BlockVerifier, config *common.ConfigEnvelope) error {
	signatureSet, err := SignatureSetFromBlock(block)
	if err != nil {
		return err
	}
	return verifier.VerifyBlockSignature(signatureSet, config)
}
221925
func VerifySignatures(s *data.Signed, roleData data.BaseRole) error {
	if len(s.Signatures) == 0 {
		return ErrNoSignatures
	}

	if roleData.Threshold < 1 {
		return ErrRoleThreshold{}
	}
	logrus.Debugf("%s role has key IDs: %s", roleData.Name, strings.Join(roleData.ListKeyIDs(), ","))

	// remarshal the signed part so we can verify the signature, since the signature has
	// to be of a canonically marshalled signed object
	var decoded map[string]interface{}
	if err := json.Unmarshal(*s.Signed, &decoded); err != nil {
		return err
	}
	msg, err := json.MarshalCanonical(decoded)
	if err != nil {
		return err
	}

	valid := make(map[string]struct{})
	for i := range s.Signatures {
		sig := &(s.Signatures[i])
		logrus.Debug("verifying signature for key ID: ", sig.KeyID)
		key, ok := roleData.Keys[sig.KeyID]
		if !ok {
			logrus.Debugf("continuing b/c keyid lookup was nil: %s\n", sig.KeyID)
			continue
		}
		// Check that the signature key ID actually matches the content ID of the key
		if key.ID() != sig.KeyID {
			return ErrInvalidKeyID{}
		}
		if err := VerifySignature(msg, sig, key); err != nil {
			logrus.Debugf("continuing b/c %s", err.Error())
			continue
		}
		valid[sig.KeyID] = struct{}{}
	}
	if len(valid) < roleData.Threshold {
		return ErrRoleThreshold{
			Msg: fmt.Sprintf("valid signatures did not meet threshold for %s", roleData.Name),
		}
	}

	return nil
}
461827
func (id *identity) Verify(msg []byte, sig []byte) error {
	// mspIdentityLogger.Infof("Verifying signature")

	// Compute Hash
	hashOpt, err := id.getHashOpt(id.msp.cryptoConfig.SignatureHashFamily)
	if err != nil {
		return errors.WithMessage(err, "failed getting hash function options")
	}

	digest, err := id.msp.bccsp.Hash(msg, hashOpt)
	if err != nil {
		return errors.WithMessage(err, "failed computing digest")
	}

	if mspIdentityLogger.IsEnabledFor(zapcore.DebugLevel) {
		mspIdentityLogger.Debugf("Verify: digest = %s", hex.Dump(digest))
		mspIdentityLogger.Debugf("Verify: sig = %s", hex.Dump(sig))
	}

	valid, err := id.msp.bccsp.Verify(id.pk, sig, digest, nil)
	if err != nil {
		return errors.WithMessage(err, "could not determine the validity of the signature")
	} else if !valid {
		return errors.New("The signature is invalid")
	}

	return nil
}