// GenerateKeyPairs generates and ed25519 signing key pair, and a curve25519
// encryption key pair for the user, encrypting the private keys in
// triplesec-v3 with the user's master key.
548472
func (e *Engine) GenerateKeyPairs(ctx context.Context) (*KeyPairs, error) {
	kp := &KeyPairs{}

	err := ctxutil.ErrIfDone(ctx)
	if err != nil {
		return nil, err
	}

	pubSig, privSig, err := ed25519.GenerateKey(rand.Reader)
	if err != nil {
		return nil, err
	}

	sealedSig, nonceSig, err := e.Seal(ctx, privSig)
	if err != nil {
		return nil, err
	}

	kp.Signature.Private = sealedSig
	kp.Signature.Public = pubSig
	kp.Signature.PNonce = nonceSig

	err = ctxutil.ErrIfDone(ctx)
	if err != nil {
		return nil, err
	}

	pubEnc, privEnc, err := box.GenerateKey(rand.Reader)
	if err != nil {
		return nil, err
	}

	sealedEnc, nonceEnc, err := e.Seal(ctx, (*privEnc)[:])
	if err != nil {
		return nil, err
	}

	kp.Encryption.Private = sealedEnc
	kp.Encryption.Public = *pubEnc
	kp.Encryption.PNonce = nonceEnc

	return kp, nil
}
947688
func (l *localKeyClient) Generate(keyName string, curveType crypto.CurveType) (keyAddress crypto.Address, err error) {
	resp, err := l.ks.GenerateKey(nil, &GenRequest{KeyName: keyName, CurveType: curveType.String()})
	if err != nil {
		return crypto.Address{}, err
	}
	return crypto.AddressFromHexString(resp.GetAddress())
}
1088095
func generateMaskingKey() (maskingKey []byte, err error) {
	maskingKey = make([]byte, 4)
	if _, err = io.ReadFull(rand.Reader, maskingKey); err != nil {
		return
	}
	return
}
473703
func X509KeyPair(certPEMBlock, keyPEMBlock []byte) (Certificate, error) {
	fail := func(err error) (Certificate, error) { return Certificate{}, err }

	var cert Certificate
	var skippedBlockTypes []string
	for {
		var certDERBlock *pem.Block
		certDERBlock, certPEMBlock = pem.Decode(certPEMBlock)
		if certDERBlock == nil {
			break
		}
		if certDERBlock.Type == "CERTIFICATE" {
			cert.Certificate = append(cert.Certificate, certDERBlock.Bytes)
		} else {
			skippedBlockTypes = append(skippedBlockTypes, certDERBlock.Type)
		}
	}

	if len(cert.Certificate) == 0 {
		if len(skippedBlockTypes) == 0 {
			return fail(errors.New("crypto/tls: failed to find any PEM data in certificate input"))
		} else if len(skippedBlockTypes) == 1 && strings.HasSuffix(skippedBlockTypes[0], "PRIVATE KEY") {
			return fail(errors.New("crypto/tls: failed to find certificate PEM data in certificate input, but did find a private key; PEM inputs may have been switched"))
		} else {
			return fail(fmt.Errorf("crypto/tls: failed to find \"CERTIFICATE\" PEM block in certificate input after skipping PEM blocks of the following types: %v", skippedBlockTypes))
		}
	}

	skippedBlockTypes = skippedBlockTypes[:0]
	var keyDERBlock *pem.Block
	for {
		keyDERBlock, keyPEMBlock = pem.Decode(keyPEMBlock)
		if keyDERBlock == nil {
			if len(skippedBlockTypes) == 0 {
				return fail(errors.New("crypto/tls: failed to find any PEM data in key input"))
			} else if len(skippedBlockTypes) == 1 && skippedBlockTypes[0] == "CERTIFICATE" {
				return fail(errors.New("crypto/tls: found a certificate rather than a key in the PEM for the private key"))
			} else {
				return fail(fmt.Errorf("crypto/tls: failed to find PEM block with type ending in \"PRIVATE KEY\" in key input after skipping PEM blocks of the following types: %v", skippedBlockTypes))
			}
		}
		if keyDERBlock.Type == "PRIVATE KEY" || strings.HasSuffix(keyDERBlock.Type, " PRIVATE KEY") {
			break
		}
		skippedBlockTypes = append(skippedBlockTypes, keyDERBlock.Type)
	}

	var err error
	cert.PrivateKey, err = parsePrivateKey(keyDERBlock.Bytes)
	if err != nil {
		return fail(err)
	}

	// We don't need to parse the public key for TLS, but we so do anyway
	// to check that it looks sane and matches the private key.
	x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
	if err != nil {
		return fail(err)
	}

	switch pub := x509Cert.PublicKey.(type) {
	case *rsa.PublicKey:
		priv, ok := cert.PrivateKey.(*rsa.PrivateKey)
		if !ok {
			return fail(errors.New("crypto/tls: private key type does not match public key type"))
		}
		if pub.N.Cmp(priv.N) != 0 {
			return fail(errors.New("crypto/tls: private key does not match public key"))
		}
	case *ecdsa.PublicKey:
		priv, ok := cert.PrivateKey.(*ecdsa.PrivateKey)
		if !ok {
			return fail(errors.New("crypto/tls: private key type does not match public key type"))

		}
		if pub.X.Cmp(priv.X) != 0 || pub.Y.Cmp(priv.Y) != 0 {
			return fail(errors.New("crypto/tls: private key does not match public key"))
		}
	default:
		return fail(errors.New("crypto/tls: unknown public key algorithm"))
	}

	return cert, nil
}
14756
func generateKey(keypath string, salt []byte, keyiter int) (key *[secret.SecretKeyLength]byte, isPass bool, err error) {
	// if a keypath is given try and use it
	if keypath != "" {
		key, err := secret.ReadKeyFromDisk(keypath)
		if err != nil {
			return nil, false, fmt.Errorf("unable to build secret service: %v", err)
		}
		return key, false, nil
	}

	// otherwise read in a passphrase from disk and use that, remember to reset your terminal afterwards
	var passphrase string
	fmt.Printf("Passphrase: ")
	fmt.Scanln(&passphrase)

	// derive key and return it
	keySlice := pbkdf2.Key([]byte(passphrase), salt, keyiter, 32, sha256.New)
	keyBytes, err := secret.KeySliceToArray(keySlice)
	if err != nil {
		return nil, true, err
	}

	return keyBytes, true, nil
}
817473
func generateKeys(d direction, algs directionAlgorithms, kex *kexResult) (iv, key, macKey []byte) {
	cipherMode := cipherModes[algs.Cipher]
	macMode := macModes[algs.MAC]

	iv = make([]byte, cipherMode.ivSize)
	key = make([]byte, cipherMode.keySize)
	macKey = make([]byte, macMode.keySize)

	generateKeyMaterial(iv, d.ivTag, kex)
	generateKeyMaterial(key, d.keyTag, kex)
	generateKeyMaterial(macKey, d.macKeyTag, kex)
	return
}
821441
func GenerateED25519Key() (PrivateKey, error) {
	// Key context
	keyCtx := C.EVP_PKEY_CTX_new_id(C.X_EVP_PKEY_ED25519, nil)
	if keyCtx == nil {
		return nil, errors.New("failed creating EC parameter generation context")
	}
	defer C.EVP_PKEY_CTX_free(keyCtx)

	// Generate the key
	var privKey *C.EVP_PKEY
	if int(C.EVP_PKEY_keygen_init(keyCtx)) != 1 {
		return nil, errors.New("failed initializing ED25519 key generation context")
	}
	if int(C.EVP_PKEY_keygen(keyCtx, &privKey)) != 1 {
		return nil, errors.New("failed generating ED25519 private key")
	}

	p := &pKey{key: privKey}
	runtime.SetFinalizer(p, func(p *pKey) {
		C.X_EVP_PKEY_free(p.key)
	})
	return p, nil
}
290816
func NewKeypairs() *Keypairs {
	return &Keypairs{
		keypairs: map[identity.ID][]ClaimedKeyPair{},
		idIndex:  map[identity.ID]ClaimedKeyPair{},
	}
}
586104
func (k *KeyStore) GenerateKey(ctx context.Context, in *GenRequest) (*GenResponse, error) {
	curveT, err := crypto.CurveTypeFromString(in.CurveType)
	if err != nil {
		return nil, err
	}

	key, err := k.Gen(in.Passphrase, curveT)
	if err != nil {
		return nil, fmt.Errorf("error generating key %s %s", curveT, err)
	}

	addrH := key.Address.String()
	if in.KeyName != "" {
		err = coreNameAdd(k.keysDirPath, in.KeyName, addrH)
		if err != nil {
			return nil, err
		}
	}

	return &GenResponse{Address: addrH}, nil
}
1284516
func (s *SetupClientSession) GenerateKeys(salt []byte, otherPublicKey []byte) error {
	privateKey, err := s.session.ComputeKey(salt, otherPublicKey)
	if err == nil {
		s.PublicKey = s.session.GetA()
		s.PrivateKey = privateKey
		s.Proof = s.session.ComputeAuthenticator()
	}

	return err
}
751974
func EncodeX509KeyPair(cert tls.Certificate) ([]byte, []byte) {

	certpem := []byte{}
	for _, certtmp := range cert.Certificate {
		certpem = append(certpem, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certtmp})...)
	}
	keypem := pem.EncodeToMemory(pemBlockForKey(cert.PrivateKey))
	return certpem, keypem
}
1117504
func (mc *CCacheMetric) generateKeys() {
	keys := make([]uint32, 0, len(mc.chunks))
	for k := range mc.chunks {
		keys = append(keys, k)
	}
	sort.Sort(accnt.Uint32Asc(keys))
	mc.keys = keys
}
1135555
func (km *KeyManagerStandard) generateKeyMapForUsers(
	ctx context.Context, users []keybase1.UserOrTeamID,
	offline keybase1.OfflineAvailability) (
	kbfsmd.UserDevicePublicKeys, error) {
	keyMap := make(kbfsmd.UserDevicePublicKeys)

	// TODO: parallelize
	for _, w := range users {
		uid := w.AsUserOrBust() // only private TLFs should call this
		// HACK: clear cache
		km.config.KeybaseService().FlushUserFromLocalCache(ctx, uid)
		publicKeys, err := km.config.KBPKI().GetCryptPublicKeys(
			ctx, uid, offline)
		if err != nil {
			return nil, err
		}
		keyMap[uid] = make(kbfsmd.DevicePublicKeys)
		for _, key := range publicKeys {
			keyMap[uid][key] = true
		}
	}

	return keyMap, nil
}
116484
func GenerateKeyPair(passphrase string) ([]byte, []byte, error) {
	priv, err := rsa.GenerateKey(rand.Reader, teleport.RSAKeySize)
	if err != nil {
		return nil, nil, err
	}
	privDer := x509.MarshalPKCS1PrivateKey(priv)
	privBlock := pem.Block{
		Type:    "RSA PRIVATE KEY",
		Headers: nil,
		Bytes:   privDer,
	}
	privPem := pem.EncodeToMemory(&privBlock)

	pub, err := ssh.NewPublicKey(&priv.PublicKey)
	if err != nil {
		return nil, nil, err
	}
	pubBytes := ssh.MarshalAuthorizedKey(pub)
	return privPem, pubBytes, nil
}
84116
func (key *Key) GenerateKey(wrapkey *Key) (err error) {
	err = tspiError(C.Tspi_Key_CreateKey((C.TSS_HKEY)(key.handle), (C.TSS_HKEY)(wrapkey.handle), 0))
	return err
}
834169
func (b *AESGCMBarrier) GenerateKey() ([]byte, error) {
	// Generate a 256bit key
	buf := make([]byte, 2*aes.BlockSize)
	_, err := rand.Read(buf)
	return buf, err
}
655861
func GenerateKeypair(ctx context.Context, c *cli.Context) error {
	if err := initCrypto(); err != nil {
		return action.ExitError(ctx, action.ExitUnknown, err, "failed to init XC")
	}

	name := c.String("name")
	email := c.String("email")
	pw := c.String("passphrase")

	if name == "" {
		var err error
		name, err = termio.AskForString(ctx, "What is your full name?", "")
		if err != nil || name == "" {
			return action.ExitError(ctx, action.ExitNoName, err, "please provide a name")
		}
	}
	if email == "" {
		var err error
		email, err = termio.AskForString(ctx, "What is your email?", "")
		if err != nil || email == "" {
			return action.ExitError(ctx, action.ExitNoName, err, "please provide an email")
		}
	}
	if pw == "" {
		var err error
		pw, err = termio.AskForPassword(ctx, "")
		if err != nil || pw == "" {
			return action.ExitError(ctx, action.ExitIO, err, "failed to ask for password: %s", err)
		}
	}

	if err := crypto.CreatePrivateKeyBatch(ctx, name, email, pw); err != nil {
		return action.ExitError(ctx, action.ExitUnknown, err, "failed to create private key: %s", err)
	}
	return nil
}