// check if (peer) symmetric key is currently registered with this topic
961495
func (p *Protocol) isActiveSymKey(key string, topic Topic) bool {
	return p.symKeyRWPool[key] != nil
}
1180663
func (engine *CryptoEngine) DecryptWithPublicKey(encryptedBytes []byte, verificationEngine VerificationEngine) (*message, error) {

	var err error

	// get the peer public key
	peerPublicKey := verificationEngine.PublicKey()

	// convert the bytes to an encrypted message
	encryptedMessage, err := encryptedMessageFromBytes(encryptedBytes)
	if err != nil {
		return nil, err
	}

	// Make sure the key has a valid size
	if len(peerPublicKey) < keySize {
		return nil, KeyNotValidError
	}

	// calculate the hash of the peer public key
	sha224String := fmt.Sprintf("%x", sha256.Sum224(peerPublicKey[:]))

	// lock the mutex
	engine.mutex.Lock()

	// check if the pre sgared key is already present in the map
	if preSharedKey, ok := engine.preSharedKeysMap[sha224String]; ok { // means the key is there
		// unlock the mutex
		engine.mutex.Unlock()

		messageBytes, err := decryptWithPreShared(preSharedKey, encryptedMessage)
		if err != nil {
			return nil, err
		}
		return messageFromBytes(messageBytes)

	} else {
		// otherwise decrypt with the standard box open function
		messageBytes, valid := box.Open(nil, encryptedMessage.data, &encryptedMessage.nonce, &peerPublicKey, &engine.privateKey)
		if !valid {
			return nil, MessageDecryptionError
		}
		return messageFromBytes(messageBytes)
	}

}
450433
func (s *Scheme) IsGroupRegistered(group string) bool {
	for _, observedVersion := range s.observedVersions {
		if observedVersion.Group == group {
			return true
		}
	}
	return false
}
1298117
func (k *KBPKIClient) HasVerifyingKey(
	ctx context.Context, uid keybase1.UID, verifyingKey kbfscrypto.VerifyingKey,
	atServerTime time.Time, offline keybase1.OfflineAvailability) error {
	ok, err := k.hasVerifyingKey(ctx, uid, verifyingKey, atServerTime, offline)
	if err != nil {
		return err
	}
	if ok {
		return nil
	}

	// If the first attempt couldn't find the key, try again after
	// clearing our local cache.  We might have stale info if the
	// service hasn't learned of the users' new key yet.
	k.serviceOwner.KeybaseService().FlushUserFromLocalCache(ctx, uid)

	ok, err = k.hasVerifyingKey(ctx, uid, verifyingKey, atServerTime, offline)
	if err != nil {
		return err
	}
	if !ok {
		return VerifyingKeyNotFoundError{verifyingKey}
	}
	return nil
}
373425
func IsForeignKeyViolation(err error, indexName string) bool {
	if err == nil {
		return false
	}
	pqError, ok := err.(*pq.Error)
	if !ok {
		return false
	}
	return pqError.Code == errForeignKeyViolation && pqError.Constraint == indexName
}
191102
func (v RSAPKCS1v15Verifier) 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)

	rsaPub, ok := pubKey.(*rsa.PublicKey)
	if !ok {
		logrus.Debugf("value was not an RSA public key")
		return ErrInvalid
	}

	if rsaPub.N.BitLen() < minRSAKeySizeBit {
		logrus.Debugf("RSA keys less than 2048 bits are not acceptable, provided key has length %d.", rsaPub.N.BitLen())
		return ErrInvalidKeyLength{msg: fmt.Sprintf("RSA key must be at least %d bits.", minRSAKeySizeBit)}
	}

	if len(sig) < minRSAKeySizeByte {
		logrus.Debugf("RSA keys less than 2048 bits are not acceptable, provided signature has length %d.", len(sig))
		return ErrInvalid
	}

	if err = rsa.VerifyPKCS1v15(rsaPub, crypto.SHA256, digest[:], sig); err != nil {
		logrus.Errorf("Failed verification: %s", err.Error())
		return ErrInvalid
	}
	return nil
}
1211002
func IsKeyEExistsError(err error) bool {

	res, ok := err.(*gomemcached.MCResponse)
	if ok && res.Status == gomemcached.KEY_EEXISTS {
		return true
	}

	return false
}
1018772
func (t *Topic) Register(ch chan<- interface{}) {
	t.lock.Lock()
	defer t.lock.Unlock()
	t.connections[ch] = nothing{}
}
683754
func (c *Certificate) isValid(certType int, currentChain []*Certificate, opts *VerifyOptions) error {
	if len(currentChain) > 0 {
		child := currentChain[len(currentChain)-1]
		if !bytes.Equal(child.RawIssuer, c.RawSubject) {
			return CertificateInvalidError{c, NameMismatch}
		}
	}
	now := opts.CurrentTime
	if now.IsZero() {
		now = time.Now()
	}
	if now.Before(c.NotBefore) || now.After(c.NotAfter) {
		return CertificateInvalidError{c, Expired}
	}
	if len(c.PermittedDNSDomains) > 0 {
		ok := false
		for _, constraint := range c.PermittedDNSDomains {
			ok = matchNameConstraint(opts.DNSName, constraint)
			if ok {
				break
			}
		}

		if !ok {
			return CertificateInvalidError{c, CANotAuthorizedForThisName}
		}
	}

	// KeyUsage status flags are ignored. From Engineering Security, Peter
	// Gutmann: A European government CA marked its signing certificates as
	// being valid for encryption only, but no-one noticed. Another
	// European CA marked its signature keys as not being valid for
	// signatures. A different CA marked its own trusted root certificate
	// as being invalid for certificate signing. Another national CA
	// distributed a certificate to be used to encrypt data for the
	// country’s tax authority that was marked as only being usable for
	// digital signatures but not for encryption. Yet another CA reversed
	// the order of the bit flags in the keyUsage due to confusion over
	// encoding endianness, essentially setting a random keyUsage in
	// certificates that it issued. Another CA created a self-invalidating
	// certificate by adding a certificate policy statement stipulating
	// that the certificate had to be used strictly as specified in the
	// keyUsage, and a keyUsage containing a flag indicating that the RSA
	// encryption key could only be used for Diffie-Hellman key agreement.

	if certType == intermediateCertificate && (!c.BasicConstraintsValid || !c.IsCA) {
		return CertificateInvalidError{c, NotAuthorizedToSign}
	}

	if c.BasicConstraintsValid && c.MaxPathLen >= 0 {
		numIntermediates := len(currentChain) - 1
		if numIntermediates > c.MaxPathLen {
			return CertificateInvalidError{c, TooManyIntermediates}
		}
	}

	return nil
}
544302
func (tm2pb) PubKey(pubKey crypto.PubKey) abci.PubKey {
	switch pk := pubKey.(type) {
	case ed25519.PubKeyEd25519:
		return abci.PubKey{
			Type: ABCIPubKeyTypeEd25519,
			Data: pk[:],
		}
	case secp256k1.PubKeySecp256k1:
		return abci.PubKey{
			Type: ABCIPubKeyTypeSecp256k1,
			Data: pk[:],
		}
	default:
		panic(fmt.Sprintf("unknown pubkey type: %v %v", pubKey, reflect.TypeOf(pubKey)))
	}
}
488342
func isWitnessPubKeyHash(pops []parsedOpcode) bool {
	return len(pops) == 2 &&
		pops[0].opcode.value == OP_0 &&
		pops[1].opcode.value == OP_DATA_20
}
782063
func (pub *DSAPublicKey) Verify(hashed, sig []byte) (nextPoint []byte, sigOk bool) {
	if len(sig) < 2*20 {
		return nil, false
	}
	r := new(big.Int).SetBytes(sig[:20])
	s := new(big.Int).SetBytes(sig[20:40])
	ok := dsa.Verify(&pub.PublicKey, hashed, r, s)
	return sig[20*2:], ok
}
152864
func (m *SigningMethodRSAPSS) Verify(raw []byte, signature Signature, key interface{}) error {
	rsaKey, ok := key.(*rsa.PublicKey)
	if !ok {
		return ErrInvalidKey
	}
	return rsa.VerifyPSS(rsaKey, m.Hash, m.sum(raw), signature, m.Options)
}
778263
func (d *Peer) NotifyPeer(a *BzzAddr, po uint8) {
	// immediately return
	if (po < d.getDepth() && pot.ProxCmp(d.kad.BaseAddr(), d, a) != 1) || d.seen(a) {
		return
	}
	resp := &peersMsg{
		Peers: []*BzzAddr{a},
	}
	go d.Send(context.TODO(), resp)
}
1227623
func (ch Challenge) CheckConsistencyForClientOffer() error {
	if err := ch.checkConsistency(); err != nil {
		return err
	}

	// Before completion, the key authorization field should be empty
	if ch.ProvidedKeyAuthorization != "" {
		return fmt.Errorf("A response to this challenge was already submitted.")
	}
	return nil
}
382647
func isPubkey(pops []parsedOpcode) bool {
	// Valid pubkeys are either 33 or 65 bytes.
	return len(pops) == 2 &&
		(len(pops[0].data) == 33 || len(pops[0].data) == 65) &&
		pops[1].opcode.value == OP_CHECKSIG
}
866668
func (s *MSPMessageCryptoService) Verify(peerIdentity api.PeerIdentityType, signature, message []byte) error {
	identity, chainID, err := s.getValidatedIdentity(peerIdentity)
	if err != nil {
		mcsLogger.Errorf("Failed getting validated identity from peer identity [%s]", err)

		return err
	}

	if len(chainID) == 0 {
		// At this stage, this means that peerIdentity
		// belongs to this peer's LocalMSP.
		// The signature is validated directly
		return identity.Verify(message, signature)
	}

	// At this stage, the signature must be validated
	// against the reader policy of the channel
	// identified by chainID

	return s.VerifyByChannel(chainID, peerIdentity, signature, message)
}