// Make a per-user key proof with a reverse sig.
// Modifies the User `me` with a sigchain bump and key delegation.
// Returns a JSONPayload ready for use in "sigs" in sig/multi.
492591
func PerUserKeyProofReverseSigned(m MetaContext, me *User, perUserKeySeed PerUserKeySeed, generation keybase1.PerUserKeyGeneration,
	signer GenericKey) (*UserLinkSignature, error) {

	pukSigKey, err := perUserKeySeed.DeriveSigningKey()
	if err != nil {
		return nil, err
	}

	pukEncKey, err := perUserKeySeed.DeriveDHKey()
	if err != nil {
		return nil, err
	}

	// Make reverse sig
	forward, err := PerUserKeyProof(m, me, pukSigKey.GetKID(), pukEncKey.GetKID(), generation, signer)
	if err != nil {
		return nil, err
	}
	reverseSig, _, _, err := SignJSON(forward.J, pukSigKey)
	if err != nil {
		return nil, err
	}

	// Make sig
	jw := forward.J
	jw.SetValueAtPath("body.per_user_key.reverse_sig", jsonw.NewString(reverseSig))
	sig, sigID, linkID, err := SignJSON(jw, signer)
	if err != nil {
		return nil, err
	}

	// Update the user locally
	me.SigChainBump(linkID, sigID, false)
	me.localDelegatePerUserKey(keybase1.PerUserKey{
		Gen:         int(generation),
		Seqno:       me.GetSigChainLastKnownSeqno(),
		SigKID:      pukSigKey.GetKID(),
		EncKID:      pukEncKey.GetKID(),
		SignedByKID: signer.GetKID(),
	})

	publicKeysEntry := make(JSONPayload)
	publicKeysEntry["signing"] = pukSigKey.GetKID().String()
	publicKeysEntry["encryption"] = pukEncKey.GetKID().String()

	payload := make(JSONPayload)
	payload["sig"] = sig
	payload["signing_kid"] = signer.GetKID().String()
	payload["type"] = LinkTypePerUserKey
	payload["public_keys"] = publicKeysEntry
	return &UserLinkSignature{
		Payload: payload,
		Seqno:   forward.Seqno,
		LinkID:  linkID,
	}, nil
}
556031
func (e *SelfProvisionEngine) makeDeviceKeysWithSigner(m libkb.MetaContext, signer libkb.GenericKey) error {
	if err := e.ensureLKSec(m); err != nil {
		return err
	}

	_, _, deviceType, err := m.G().GetUPAKLoader().LookupUsernameAndDevice(m.Ctx(), e.User.GetUID(), e.G().ActiveDevice.DeviceID())
	if err != nil {
		return err
	}

	args := &DeviceWrapArgs{
		Me:              e.User,
		DeviceName:      e.DeviceName,
		DeviceType:      deviceType,
		Lks:             e.lks,
		IsEldest:        false, // just to be explicit
		IsSelfProvision: true,
		PerUserKeyring:  e.perUserKeyring,
		EldestKID:       e.User.GetEldestKID(),
		Signer:          signer,
		EkReboxer:       e.ekReboxer,
	}

	e.deviceWrapEng = NewDeviceWrap(m.G(), args)
	return RunEngine2(m, e.deviceWrapEng)
}
549920
func GenSecpPrivKeys(n int) privKeys {
	res := make(privKeys, n)
	for i := range res {
		res[i] = secp256k1.GenPrivKey()
	}
	return res
}
1215451
func (lu *LocalUser) GetPublicKeys() []keybase1.PublicKey {
	sibkeys := verifyingKeysToPublicKeys(lu.VerifyingKeys)
	subkeys := cryptPublicKeysToPublicKeys(lu.CryptPublicKeys)
	return append(sibkeys, subkeys...)
}
508265
func (p *siprng) rekey() {
	var k [16]byte
	if _, err := io.ReadFull(rand.Reader, k[:]); err != nil {
		panic(err.Error())
	}
	p.k0 = binary.LittleEndian.Uint64(k[0:8])
	p.k1 = binary.LittleEndian.Uint64(k[8:16])
	p.ctr = 1
}
497740
func (m *tokenManager) GenerateTransientUserAccessTokenForIdentity(ctx context.Context, identity repository.Identity) (*string, error) {
	token, err := m.GenerateUnsignedUserAccessTokenForIdentity(ctx, identity)
	if err != nil {
		return nil, err
	}

	claims := token.Claims.(jwt.MapClaims)
	iat := time.Now().Unix()
	claims["exp"] = iat + m.config.GetTransientTokenExpiresIn()
	claims["transient"] = "true"

	accessToken, err := token.SignedString(m.userAccountPrivateKey.Key)
	if err != nil {
		return nil, errors.WithStack(err)
	}

	return &accessToken, nil
}
303006
func MakeNaclSigningKeyPairFromSecret(secret [NaclSigningKeySecretSize]byte) (NaclSigningKeyPair, error) {
	r := bytes.NewReader(secret[:])

	kp, err := makeNaclSigningKeyPair(r)
	if err != nil {
		return NaclSigningKeyPair{}, err
	}

	if r.Len() > 0 {
		return NaclSigningKeyPair{}, fmt.Errorf("Did not use %d secret byte(s)", r.Len())
	}

	return kp, err
}
134768
func GenerateKeypair() (pub string, priv string, err error) {
	var kp crypto.Keypair
	if err := kp.Generate(); err != nil {
		return "", "", err
	}
	return kp.PublicString(), kp.PrivateString(), nil
}
633066
func MakeLocalUserSigningKeyOrBust(
	name kbname.NormalizedUsername) kbfscrypto.SigningKey {
	return kbfscrypto.MakeFakeSigningKeyOrBust(
		string(name) + " signing key")
}
311871
func buildInternalNkeyUser(uc *jwt.UserClaims, acc *Account) *NkeyUser {
	nu := &NkeyUser{Nkey: uc.Subject, Account: acc}
	if uc.IssuerAccount != "" {
		nu.SigningKey = uc.Issuer
	}

	// Now check for permissions.
	var p *Permissions

	if len(uc.Pub.Allow) > 0 || len(uc.Pub.Deny) > 0 {
		if p == nil {
			p = &Permissions{}
		}
		p.Publish = &SubjectPermission{}
		p.Publish.Allow = uc.Pub.Allow
		p.Publish.Deny = uc.Pub.Deny
	}
	if len(uc.Sub.Allow) > 0 || len(uc.Sub.Deny) > 0 {
		if p == nil {
			p = &Permissions{}
		}
		p.Subscribe = &SubjectPermission{}
		p.Subscribe.Allow = uc.Sub.Allow
		p.Subscribe.Deny = uc.Sub.Deny
	}
	nu.Permissions = p
	return nu
}
151602
func openPerUserKeyPrev(sbox PerUserKeyPrev, symmetricKey NaclSecretBoxKey) (PerUserKeySeed, error) {
	var res PerUserKeySeed

	// decode b64
	msgpacked, err := base64.StdEncoding.DecodeString(string(sbox))
	if err != nil {
		return res, err
	}

	// decode msgpack
	mh := codec.MsgpackHandle{WriteExt: true}
	dec := codec.NewDecoderBytes(msgpacked, &mh)
	var parts struct {
		Version int
		Nonce   []byte
		Sealed  []byte
	}
	err = dec.Decode(&parts)
	if err != nil {
		return res, err
	}

	// check parts
	if parts.Version != 1 {
		return res, fmt.Errorf("per user key secret box version %v != 1", parts.Version)
	}

	if len(parts.Nonce) != NaclDHNonceSize {
		return res, fmt.Errorf("per user key secret box nonce length %v != %v",
			len(parts.Nonce), NaclDHNonceSize)
	}
	var nonce [NaclDHNonceSize]byte
	copy(nonce[:], parts.Nonce)

	expectedSealedLength := PerUserKeySeedSize + secretbox.Overhead
	if len(parts.Sealed) != expectedSealedLength {
		return res, fmt.Errorf("per user key secret box sealed length %v != %v", len(parts.Sealed), expectedSealedLength)
	}

	// open secretbox
	var symmetricKey2 [NaclSecretBoxKeySize]byte = symmetricKey
	contents, ok := secretbox.Open(nil, parts.Sealed, &nonce, &symmetricKey2)
	if !ok {
		return res, errors.New("per user key secret box open failed")
	}
	if len(contents) != PerUserKeySeedSize {
		return res, fmt.Errorf("per user key seed length %v != %v", len(contents), PerUserKeySeedSize)
	}
	return MakeByte32(contents), nil
}
679800
func Convert_v1_User_To_user_User(in *v1.User, out *user.User, s conversion.Scope) error {
	return autoConvert_v1_User_To_user_User(in, out, s)
}
225256
func parseCAKey(bytes []byte, allowedLogins []string) (services.CertAuthority, services.Role, error) {
	caFormat, err := certificateAuthorityFormat(bytes)
	if err != nil {
		return nil, nil, trace.Wrap(err)
	}

	if caFormat == teleport.AuthorizedKeys {
		return parseAuthorizedKeys(bytes, allowedLogins)
	}
	return parseKnownHosts(bytes, allowedLogins)
}
648149
func (s *SecretStoreRevokableSecretService) GetUsersWithStoredSecrets(mctx MetaContext) (usernames []string, err error) {
	defer mctx.TraceTimed("SecretStoreRevokableSecretService.GetUsersWithStoredSecrets", func() error { return err })()
	identifierKeystore := s.identifierKeystore(mctx)
	suffixedUsernames, err := identifierKeystore.AllKeys(mctx, identifierKeystoreSuffix)
	if err != nil {
		return nil, err
	}
	for _, suffixedUsername := range suffixedUsernames {
		usernames = append(usernames, strings.TrimSuffix(suffixedUsername, identifierKeystoreSuffix))
	}
	return usernames, nil
}
1017871
func (v *CredentialAuthority) makeUser(uid keybase1.UID) *user {
	uw := v.users[uid]
	if uw == nil {
		u := newUser(uid, v)
		uw = &userWrapper{u: u}
		v.users[uid] = uw
	}
	uw.atime = v.eng.Now()
	return uw.u
}
833312
func (pk *PublicKey) VerifyKeySignature(signed *PublicKey, sig *Signature) error {
	h, err := keySignatureHash(pk, signed, sig.Hash)
	if err != nil {
		return err
	}
	if err = pk.VerifySignature(h, sig); err != nil {
		return err
	}

	if sig.FlagSign {
		// Signing subkeys must be cross-signed. See
		// https://www.gnupg.org/faq/subkey-cross-certify.html.
		if sig.EmbeddedSignature == nil {
			return errors.StructuralError("signing subkey is missing cross-signature")
		}
		// Verify the cross-signature. This is calculated over the same
		// data as the main signature, so we cannot just recursively
		// call signed.VerifyKeySignature(...)
		if h, err = keySignatureHash(pk, signed, sig.EmbeddedSignature.Hash); err != nil {
			return errors.StructuralError("error while hashing for cross-signature: " + err.Error())
		}
		if err := signed.VerifySignature(h, sig.EmbeddedSignature); err != nil {
			return errors.StructuralError("error while verifying cross-signature: " + err.Error())
		}
	}

	return 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()
}