// Delegate performs a delegation to the key described in the given TypedChainLink.
// This maybe be a sub- or sibkey delegation.
341317
func (ckf *ComputedKeyFamily) Delegate(tcl TypedChainLink) (err error) {

	kid := tcl.GetDelegatedKid()
	sigid := tcl.GetSigID()
	tm := TclToKeybaseTime(tcl)

	if kid.IsNil() {
		debug.PrintStack()
		return KeyFamilyError{fmt.Sprintf("Delegated KID is nil %T", tcl)}
	}

	if _, err := ckf.FindKeyWithKIDUnsafe(kid); err != nil {
		return KeyFamilyError{fmt.Sprintf("Delegated KID %s is not in the key family", kid.String())}
	}

	mhm, err := tcl.GetMerkleHashMeta()
	if err != nil {
		return err
	}

	err = ckf.cki.Delegate(kid, tm, sigid, tcl.GetKID(), tcl.GetParentKid(),
		tcl.GetPGPFullHash(), (tcl.GetRole() == DLGSibkey), tcl.GetCTime(), tcl.GetETime(),
		mhm, tcl.GetFirstAppearedMerkleSeqnoUnverified(), tcl.ToSigChainLocation())
	return
}
577854
func (ckf *ComputedKeyFamily) Revoke(tcl TypedChainLink) (err error) {
	err = ckf.revokeSigs(tcl.GetRevocations(), tcl)
	if err == nil {
		err = ckf.revokeKids(tcl.GetRevokeKids(), tcl)
	}
	return err
}
579581
func (c *Call) RoutingDelegate() string {
	if c == nil {
		return ""
	}
	return c.ic.req.RoutingDelegate
}
607662
func (d *delegationCommander) delegationAdd(cmd *cobra.Command, args []string) error {
	// We must have at least the gun and role name, and at least one key or path (or the --all-paths flag) to add
	if len(args) < 2 || len(args) < 3 && d.paths == nil && !d.allPaths {
		cmd.Usage()
		return fmt.Errorf("must specify the Global Unique Name and the role of the delegation along with the public key certificate paths and/or a list of paths to add")
	}

	config, err := d.configGetter()
	if err != nil {
		return err
	}

	gun := data.GUN(args[0])
	role := data.RoleName(args[1])

	pubKeys, err := ingestPublicKeys(args)
	if err != nil {
		return err
	}

	checkAllPaths(d)

	trustPin, err := getTrustPinning(config)
	if err != nil {
		return err
	}

	// no online operations are performed by add so the transport argument
	// should be nil
	nRepo, err := notaryclient.NewFileCachedRepository(
		config.GetString("trust_dir"), gun, getRemoteTrustServer(config), nil, d.retriever, trustPin)
	if err != nil {
		return err
	}

	// Add the delegation to the repository
	err = nRepo.AddDelegation(role, pubKeys, d.paths)
	if err != nil {
		return fmt.Errorf("failed to create delegation: %v", err)
	}

	// Make keyID slice for better CLI print
	pubKeyIDs := []string{}
	for _, pubKey := range pubKeys {
		pubKeyID, err := utils.CanonicalKeyID(pubKey)
		if err != nil {
			return err
		}
		pubKeyIDs = append(pubKeyIDs, pubKeyID)
	}

	cmd.Println("")
	addingItems := ""
	if len(pubKeyIDs) > 0 {
		addingItems = addingItems + fmt.Sprintf("with keys %s, ", pubKeyIDs)
	}
	if d.paths != nil || d.allPaths {
		addingItems = addingItems + fmt.Sprintf(
			"with paths [%s], ",
			strings.Join(prettyPaths(d.paths), "\n"),
		)
	}
	cmd.Printf(
		"Addition of delegation role %s %sto repository \"%s\" staged for next publish.\n",
		role, addingItems, gun)
	cmd.Println("")

	return maybeAutoPublish(cmd, d.autoPublish, gun, config, d.retriever)
}
247246
func (j *JWT) KeyFunc(token *gojwt.Token) (interface{}, error) {
	if _, ok := token.Method.(*gojwt.SigningMethodHMAC); ok {
		return []byte(j.Secret), nil
	} else if _, ok := token.Method.(*gojwt.SigningMethodRSA); ok {
		return j.KeyFuncRS256(token)
	}
	return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
953736
func (kf *KeyFormat) KeyBytes(segments ...[]byte) ([]byte, error) {
	key := make([]byte, kf.length)
	n := copy(key, kf.prefix)
	var offset int
	for i, l := range kf.layout {
		si := i + offset
		if len(segments) <= si {
			break
		}
		s := segments[si]
		switch l {
		case VariadicSegmentLength:
			// Must be a final variadic element
			key = append(key, s...)
			n += len(s)
		case DelimiterSegmentLength:
			// ignore
			offset--
		default:
			if len(s) != l {
				return nil, fmt.Errorf("the segment '0x%X' provided to KeyFormat.KeyBytes() does not have required "+
					"%d bytes required by layout for segment %d", s, l, i)
			}
			n += l
			// Big endian so pad on left if not given the full width for this segment
			copy(key[n-len(s):n], s)
		}
	}
	return key[:n], nil
}
1328219
func (r *ValidationResult) Key(key string) *ValidationResult {
	if r.Error != nil {
		r.Error.Key = key
	}
	return r
}
28021
func (c *ConfigLocal) KeyBundleCache() kbfsmd.KeyBundleCache {
	c.lock.RLock()
	defer c.lock.RUnlock()
	return c.kbcache
}
888105
func (d *Delegator) Run(m MetaContext) (err error) {
	var jw *jsonw.Wrapper
	defer m.Trace("Delegator#Run", func() error { return err })()

	if err = d.CheckArgs(m); err != nil {
		return err
	}

	d.MerkleRoot = m.G().MerkleClient.LastRoot()

	// We'll need to generate two proofs, so set the Ctime
	// so that we get the same time both times
	d.Ctime = m.G().Clock().Now().Unix()

	// For a sibkey signature, we first sign the blob with the
	// sibkey, and then embed that signature for the delegating key
	if d.DelegationType == DelegationTypeSibkey {
		if jw, err = KeyProof(m, *d); err != nil {
			m.Debug("| Failure in intermediate KeyProof()")
			return err
		}

		if d.RevSig, _, _, err = SignJSON(jw, d.NewKey); err != nil {
			m.Debug("| Failure in intermediate SignJson()")
			return err
		}
	}

	if m.G().LocalDb == nil {
		panic("should have a local DB")
	}

	proof, err := KeyProof2(m, *d)
	if err != nil {
		m.Debug("| Failure in KeyProof2()")
		return err
	}

	return d.SignAndPost(m, proof)
}
1142407
func (s *dirStore) key(parent, scope string) string {
	data := scope + "." + parent
	sum := md5.Sum([]byte(data))
	return hex.EncodeToString(sum[:])
}
789465
func (c *TokenController) Keys(ctx *app.KeysTokenContext) error {
	var publicKeys token.JSONKeys
	if ctx.Format != nil && *ctx.Format == "pem" {
		publicKeys = c.TokenManager.PemKeys()
	} else {
		publicKeys = c.TokenManager.JSONWebKeys()
	}

	return ctx.OK(&app.PublicKeys{Keys: publicKeys.Keys})
}
963615
func NewDelegateUICtlHandler(xp rpc.Transporter, id libkb.ConnectionID, g *libkb.GlobalContext, rekeyMaster *rekeyMaster) *DelegateUICtlHandler {
	return &DelegateUICtlHandler{
		Contextified: libkb.NewContextified(g),
		BaseHandler:  NewBaseHandler(g, xp),
		id:           id,
		rekeyMaster:  rekeyMaster,
	}
}
90701
func (b *GCSBuilder) Key() ([gcs.KeySize]byte, error) {
	// Do nothing if the builder's errored out.
	if b.err != nil {
		return [gcs.KeySize]byte{}, b.err
	}

	return b.key, nil
}
700553
func (stub *ChaincodeStub) InvokeChaincode(chaincodeName string, args [][]byte, channel string) pb.Response {
	// Internally we handle chaincode name as a composite name
	if channel != "" {
		chaincodeName = chaincodeName + "/" + channel
	}
	return stub.handler.handleInvokeChaincode(chaincodeName, args, stub.ChannelId, stub.TxID)
}
757942
func (c *ConfigLocal) KeyCache() KeyCache {
	c.lock.RLock()
	defer c.lock.RUnlock()
	return c.kcache
}
7121
func (v *VserverEntry) Key() string {
	return fmt.Sprintf("%d/%s", v.Port, v.Proto)
}
627239
func (f *Facade) generateDelegateKey(ctx datastore.Context, entity *host.Host) ([]byte, error) {
	// Generate new key
	delegateHeaders := map[string]string{
		"purpose": "delegate",
		"host_ip": entity.IPAddr,
		"host_id": entity.ID}
	publicPEM, privatePEM, err := auth.GenerateRSAKeyPairPEM(delegateHeaders)
	if err != nil {
		return nil, err
	}

	// Get the master public key
	masterHeaders := map[string]string{"purpose": "master"}
	masterPublicKey, err := auth.GetMasterPublicKey()
	if err != nil {
		return nil, err
	}
	masterPEM, err := auth.PEMFromRSAPublicKey(masterPublicKey, masterHeaders)
	if err != nil {
		return nil, err
	}

	// Store the key
	hostkeyEntity := hostkey.HostKey{PEM: string(publicPEM[:])}
	err = f.hostkeyStore.Put(ctx, entity.ID, &hostkeyEntity)
	if err != nil {
		return nil, err
	}

	// Reset the host's "authenticated" status
	f.RemoveHostExpiration(ctx, entity.ID)

	// Concatenate and return keys
	delegatePEMBlock := append(privatePEM, masterPEM...)
	return delegatePEMBlock, nil
}