// Returns a keying material. See sections of
// https://tools.ietf.org/html/draft-ietf-webpush-encryption-07#section-3.3
491994
func newKeyInfo(subscriptionPublicKey, serverPublicKey []byte) []byte {
	info := make([]byte, len(keyInfoPrefix)+len(subscriptionPublicKey)+len(serverPublicKey))
	n := copy(info, keyInfoPrefix)
	n += copy(info[n:], subscriptionPublicKey)
	copy(info[n:], serverPublicKey)
	return info
}
643007
func getKeyHash(key interface{}) uintptr {
	switch x := key.(type) {
	case string:
		return getStringHash(x)
	case []byte:
		return uintptr(siphash.Hash(sipHashKey1, sipHashKey2, x))
	case int:
		return getUintptrHash(uintptr(x))
	case int8:
		return getUintptrHash(uintptr(x))
	case int16:
		return getUintptrHash(uintptr(x))
	case int32:
		return getUintptrHash(uintptr(x))
	case int64:
		return getUintptrHash(uintptr(x))
	case uint:
		return getUintptrHash(uintptr(x))
	case uint8:
		return getUintptrHash(uintptr(x))
	case uint16:
		return getUintptrHash(uintptr(x))
	case uint32:
		return getUintptrHash(uintptr(x))
	case uint64:
		return getUintptrHash(uintptr(x))
	case uintptr:
		return getUintptrHash(x)
	}
	panic(fmt.Errorf("unsupported key type %T", key))
}
549590
func (s *PerUserKeyring) GetEncryptionKeyByGeneration(m MetaContext, gen keybase1.PerUserKeyGeneration) (*NaclDHKeyPair, error) {
	s.Lock()
	defer s.Unlock()

	return s.getEncryptionKeyByGenerationLocked(m, gen)
}
580084
func DecryptKey(keyjson []byte, auth string) (*Key, error) {
	// Parse the json into a simple map to fetch the key version
	m := make(map[string]interface{})
	if err := json.Unmarshal(keyjson, &m); err != nil {
		return nil, err
	}
	// Depending on the version try to parse one way or another
	var (
		keyBytes, keyId []byte
		err             error
	)
	if version, ok := m["version"].(string); ok && version == "1" {
		k := new(encryptedKeyJSONV1)
		if err := json.Unmarshal(keyjson, k); err != nil {
			return nil, err
		}
		keyBytes, keyId, err = decryptKeyV1(k, auth)
	} else {
		k := new(encryptedKeyJSONV3)
		if err := json.Unmarshal(keyjson, k); err != nil {
			return nil, err
		}
		keyBytes, keyId, err = decryptKeyV3(k, auth)
	}
	// Handle any decryption errors and return the key
	if err != nil {
		return nil, err
	}
	key := crypto.ToECDSAUnsafe(keyBytes)

	return &Key{
		Id:         uuid.UUID(keyId),
		Address:    crypto.PubkeyToAddress(key.PublicKey),
		PrivateKey: key,
	}, nil
}
566411
func (g *GlobalContext) GetPerUserKeyring(ctx context.Context) (ret *PerUserKeyring, err error) {
	defer g.Trace("G#GetPerUserKeyring", func() error { return err })()

	myUID := g.ActiveDevice.UID()
	if myUID.IsNil() {
		return nil, errors.New("PerUserKeyring unavailable with no UID")
	}

	// Don't do any operations under these locks that could come back and hit them again.
	// That's why GetMyUID up above is not under this lock.
	g.perUserKeyringMu.Lock()
	defer g.perUserKeyringMu.Unlock()

	makeNew := func() (*PerUserKeyring, error) {
		pukring, err := NewPerUserKeyring(g, myUID)
		if err != nil {
			g.Log.CWarningf(ctx, "G#GetPerUserKeyring -> failed: %s", err)
			g.perUserKeyring = nil
			return nil, err
		}
		g.Log.CDebugf(ctx, "G#GetPerUserKeyring -> new")
		g.perUserKeyring = pukring
		return g.perUserKeyring, nil
	}

	if g.perUserKeyring == nil {
		return makeNew()
	}
	pukUID := g.perUserKeyring.GetUID()
	if pukUID.Equal(myUID) {
		return g.perUserKeyring, nil
	}
	return makeNew()
}
948950
func (apiDef *APIDefinition) GetSecurityScheme(name string) (SecurityScheme, bool) {
	var ss SecurityScheme
	var ok bool

	// split library name by '.'
	// if there is '.', it means we need to look from the library
	splitted := strings.Split(strings.TrimSpace(name), ".")

	switch len(splitted) {
	case 1:
		ss, ok = apiDef.SecuritySchemes[name]
	case 2:
		var l *Library
		l, ok = apiDef.Libraries[splitted[0]]
		if !ok {
			return ss, false
		}
		ss, ok = l.SecuritySchemes[splitted[1]]
	}
	return ss, ok
}
1054280
func GetKey(b []byte) Key {
	for _, k := range ASCIISequences {
		if bytes.Equal(k.ASCIICode, b) {
			return k.Key
		}
	}
	return NotDefined
}
445476
func (ppm *ProtoProducerMessage) GetKey() string {
	key, _ := ppm.Key.Encode()
	return string(key)
}
1158891
func (c *PassphraseChange) findAndDecryptPrivatePGPKeys(m libkb.MetaContext) ([]libkb.GenericKey, error) {

	var keyList []libkb.GenericKey

	// Using a paper key makes TripleSec-synced keys unrecoverable
	if c.usingPaper {
		m.Debug("using a paper key, thus TripleSec-synced keys are unrecoverable")
		return keyList, nil
	}

	// Only use the synced secret keys:
	blocks, err := c.me.AllSyncedSecretKeys(m)
	if err != nil {
		return nil, err
	}

	secretRetriever := libkb.NewSecretStore(c.G(), c.me.GetNormalizedName())

	for _, block := range blocks {
		parg := m.SecretKeyPromptArg(libkb.SecretKeyArg{}, "passphrase change")
		key, err := block.PromptAndUnlock(m, parg, secretRetriever, c.me)
		if err != nil {
			return nil, err
		}
		keyList = append(keyList, key)
	}

	return keyList, nil
}
826392
func GetKeyDERFromPEM(in []byte, password []byte) ([]byte, error) {
	keyDER, _ := pem.Decode(in)
	if keyDER != nil {
		if procType, ok := keyDER.Headers["Proc-Type"]; ok {
			if strings.Contains(procType, "ENCRYPTED") {
				if password != nil {
					return x509.DecryptPEMBlock(keyDER, password)
				}
				return nil, cferr.New(cferr.PrivateKeyError, cferr.Encrypted)
			}
		}
		return keyDER.Bytes, nil
	}

	return nil, cferr.New(cferr.PrivateKeyError, cferr.DecodeFailed)
}
746020
func keyFunc(name, namespace string, tr *authenticationv1.TokenRequest) string {
	var exp int64
	if tr.Spec.ExpirationSeconds != nil {
		exp = *tr.Spec.ExpirationSeconds
	}

	var ref authenticationv1.BoundObjectReference
	if tr.Spec.BoundObjectRef != nil {
		ref = *tr.Spec.BoundObjectRef
	}

	return fmt.Sprintf("%q/%q/%#v/%#v/%#v", name, namespace, tr.Spec.Audiences, exp, ref)
}
801463
func getMetadataInnerSingle(ctx context.Context, g *libkb.GlobalContext,
	folder *keybase1.Folder, responseRepo ServerResponseRepo) (info *keybase1.GitRepoInfo, skip bool, err error) {

	cryptoer := NewCrypto(g)

	// If the folder was passed in, use it. Otherwise, load the team to
	// figure it out.
	var repoFolder keybase1.Folder
	if folder != nil {
		repoFolder = *folder
	} else {
		repoFolder, err = folderFromTeamID(ctx, g, responseRepo.TeamID, responseRepo.IsImplicit)
		if err != nil {
			return nil, false, err
		}

		// Currently we want to pretend that multi-user personal repos
		// (/keybase/{private,public}/chris,max/...) don't exist. Short circuit here
		// to keep those out of the results list.
		if repoFolder.Name != g.Env.GetUsername().String() &&
			(repoFolder.FolderType == keybase1.FolderType_PRIVATE || repoFolder.FolderType == keybase1.FolderType_PUBLIC) {

			return nil, true, nil
		}
	}

	teamIDVis := keybase1.TeamIDWithVisibility{
		TeamID: responseRepo.TeamID,
	}
	if repoFolder.Private {
		teamIDVis.Visibility = keybase1.TLFVisibility_PRIVATE
	} else {
		teamIDVis.Visibility = keybase1.TLFVisibility_PUBLIC
	}

	ciphertext, err := base64.StdEncoding.DecodeString(responseRepo.EncryptedMetadata)
	if err != nil {
		return nil, false, err
	}

	nonceSlice, err := base64.StdEncoding.DecodeString(responseRepo.Nonce)
	if err != nil {
		return nil, false, err
	}
	if len(nonceSlice) != len(keybase1.BoxNonce{}) {
		return nil, false, fmt.Errorf("expected a nonce of length %d, found %d", len(keybase1.BoxNonce{}), len(nonceSlice))
	}
	var nonce keybase1.BoxNonce
	copy(nonce[:], nonceSlice)

	encryptedMetadata := keybase1.EncryptedGitMetadata{
		V:   responseRepo.EncryptionVersion,
		E:   ciphertext,
		N:   nonce,
		Gen: responseRepo.KeyGeneration,
	}
	msgpackPlaintext, err := cryptoer.Unbox(ctx, teamIDVis, &encryptedMetadata)
	if err != nil {
		return nil, false, fmt.Errorf("repo tid:%v visibility:%s: %v", teamIDVis.TeamID, teamIDVis.Visibility, err)
	}

	var localMetadataVersioned keybase1.GitLocalMetadataVersioned
	mh := codec.MsgpackHandle{WriteExt: true}
	dec := codec.NewDecoderBytes(msgpackPlaintext, &mh)
	err = dec.Decode(&localMetadataVersioned)
	if err != nil {
		return nil, false, err
	}

	// Translate back from GitLocalMetadataVersioned to the decoupled type
	// that we use for local RPC.
	version, err := localMetadataVersioned.Version()
	if err != nil {
		return nil, false, err
	}
	var localMetadata keybase1.GitLocalMetadata
	switch version {
	case keybase1.GitLocalMetadataVersion_V1:
		localMetadata = keybase1.GitLocalMetadata{
			RepoName: localMetadataVersioned.V1().RepoName,
		}
	default:
		return nil, false, fmt.Errorf("unrecognized variant of GitLocalMetadataVersioned: %#v", version)
	}

	// Load UPAKs to get the last writer username and device name.
	lastWriterUPAK, _, err := g.GetUPAKLoader().LoadV2(libkb.NewLoadUserArgWithContext(ctx, g).
		WithUID(responseRepo.LastModifyingUID).
		WithPublicKeyOptional())
	if err != nil {
		return nil, false, err
	}
	var deviceName string
	for _, upk := range append([]keybase1.UserPlusKeysV2{lastWriterUPAK.Current}, lastWriterUPAK.PastIncarnations...) {
		for _, deviceKey := range upk.DeviceKeys {
			if deviceKey.DeviceID.Eq(responseRepo.LastModifyingDeviceID) {
				deviceName = deviceKey.DeviceDescription
				break
			}
		}
	}
	if deviceName == "" {
		return nil, false, fmt.Errorf("can't find device name for %s's device ID %s", lastWriterUPAK.Current.Username, responseRepo.LastModifyingDeviceID)
	}

	var settings *keybase1.GitTeamRepoSettings
	if repoFolder.FolderType == keybase1.FolderType_TEAM {
		pset, err := convertTeamRepoSettings(ctx, g, responseRepo.TeamID, responseRepo.ChatConvID, responseRepo.ChatDisabled)
		if err != nil {
			return nil, false, err
		}
		settings = &pset
	}

	return &keybase1.GitRepoInfo{
		Folder:         repoFolder,
		RepoID:         responseRepo.RepoID,
		RepoUrl:        formatRepoURL(repoFolder, string(localMetadata.RepoName)),
		GlobalUniqueID: formatUniqueRepoID(responseRepo.TeamID, responseRepo.RepoID),
		CanDelete:      responseRepo.Role.IsAdminOrAbove(),
		LocalMetadata:  localMetadata,
		ServerMetadata: keybase1.GitServerMetadata{
			Ctime:                   keybase1.ToTime(responseRepo.CTime),
			Mtime:                   keybase1.ToTime(responseRepo.MTime),
			LastModifyingUsername:   lastWriterUPAK.Current.Username,
			LastModifyingDeviceID:   responseRepo.LastModifyingDeviceID,
			LastModifyingDeviceName: deviceName,
		},
		TeamRepoSettings: settings,
	}, false, nil
}
756092
func (csp *impl) KeyGen(opts bccsp.KeyGenOpts) (k bccsp.Key, err error) {
	return nil, nil
}
258505
func (k *KBPKIClient) GetTeamTLFCryptKeys(
	ctx context.Context, tid keybase1.TeamID, desiredKeyGen kbfsmd.KeyGen,
	offline keybase1.OfflineAvailability) (
	map[kbfsmd.KeyGen]kbfscrypto.TLFCryptKey, kbfsmd.KeyGen, error) {
	teamInfo, err := k.serviceOwner.KeybaseService().LoadTeamPlusKeys(
		ctx, tid, tlf.Unknown, desiredKeyGen, keybase1.UserVersion{},
		kbfscrypto.VerifyingKey{}, keybase1.TeamRole_NONE, offline)
	if err != nil {
		return nil, 0, err
	}
	return teamInfo.CryptKeys, teamInfo.LatestKeyGen, nil
}
450828
func (p *parser) keyString(it item) string {
	switch it.typ {
	case itemText:
		return it.val
	case itemString, itemMultilineString,
		itemRawString, itemRawMultilineString:
		s, _ := p.value(it)
		return s.(string)
	default:
		p.bug("Unexpected key type: %s", it.typ)
		panic("unreachable")
	}
}
816977
func (c *CryptoSuite) KeyGen(opts core.KeyGenOpts) (k core.Key, err error) {
	key, err := c.BCCSP.KeyGen(opts)
	return GetKey(key), err
}
320483
func RetrieveGPGKey(pgpKey string) (string, error) {
	const keybasePrefix = "keybase:"

	encryptionKey := pgpKey
	if strings.HasPrefix(pgpKey, keybasePrefix) {
		publicKeys, err := pgpkeys.FetchKeybasePubkeys([]string{pgpKey})
		if err != nil {
			return "", errwrap.Wrapf(fmt.Sprintf("Error retrieving Public Key for %s: {{err}}", pgpKey), err)
		}
		encryptionKey = publicKeys[pgpKey]
	}

	return encryptionKey, nil
}