// MakeSubjCertKeyPair generates a private key and a certificate for subject
// suitable for securing TLS communication
359030
func (u CertTestUtil) MakeSubjCertKeyPair(cn, ou string, keyValidPeriod time.Duration, caCertTpl *x509.Certificate, caPrivKey *rsa.PrivateKey) (subjCertBytes []byte, subjPrivKey *rsa.PrivateKey, err error) {
	subjPrivKey, err = rsa.GenerateKey(rand.Reader, keyBitsDefault)
	if err != nil {
		return nil, nil, err
	}
	subjPubBytes, err := x509.MarshalPKIXPublicKey(subjPrivKey.Public())
	if err != nil {
		return nil, nil, err
	}
	subjPubSha256 := sha256.Sum256(subjPubBytes)
	subjCertTpl := x509.Certificate{
		SignatureAlgorithm: defaultSignatureAlgorithm,
		PublicKeyAlgorithm: defaultPublicKeyAlgorithm,
		Version:            3,
		SerialNumber:       big.NewInt(1),
		Subject: pkix.Name{
			OrganizationalUnit: []string{ou},
			CommonName:         cn,
		},
		NotBefore:    time.Now(),
		NotAfter:     time.Now().Add(keyValidPeriod),
		KeyUsage:     x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment | x509.KeyUsageDataEncipherment | x509.KeyUsageKeyAgreement,
		ExtKeyUsage:  []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth},
		SubjectKeyId: subjPubSha256[:],
	}
	subjCertTpl.DNSNames = []string{"localhost"}
	subjCertTpl.IPAddresses = []net.IP{net.ParseIP("127.0.0.1")}
	subjCertBytes, err = x509.CreateCertificate(rand.Reader, &subjCertTpl, caCertTpl, subjPrivKey.Public(), caPrivKey)
	return subjCertBytes, subjPrivKey, err
}
671244
func signCertWithPrivateKey(pk string, certificate string) (ssh.AuthMethod, error) {
	rawPk, err := ssh.ParseRawPrivateKey([]byte(pk))
	if err != nil {
		return nil, fmt.Errorf("failed to parse private key %q: %s", pk, err)
	}

	pcert, _, _, _, err := ssh.ParseAuthorizedKey([]byte(certificate))
	if err != nil {
		return nil, fmt.Errorf("failed to parse certificate %q: %s", certificate, err)
	}

	usigner, err := ssh.NewSignerFromKey(rawPk)
	if err != nil {
		return nil, fmt.Errorf("failed to create signer from raw private key %q: %s", rawPk, err)
	}

	ucertSigner, err := ssh.NewCertSigner(pcert.(*ssh.Certificate), usigner)
	if err != nil {
		return nil, fmt.Errorf("failed to create cert signer %q: %s", usigner, err)
	}

	return ssh.PublicKeys(ucertSigner), nil
}
20271
func (k *KeyPairsClient) Create(ctx context.Context, pubKey *envelope.PublicKey,
	privKey *envelope.PrivateKey, claim *envelope.Claim) (*envelope.PublicKey,
	*envelope.PrivateKey, []envelope.Claim, error) {

	req := ClaimedKeyPair{
		PublicKeySegment: apitypes.PublicKeySegment{
			PublicKey: pubKey,
			Claims:    []envelope.Claim{*claim},
		},
		PrivateKey: privKey,
	}
	resp := ClaimedKeyPair{}
	err := k.client.RoundTrip(ctx, "POST", "/keypairs", nil, &req, &resp)
	if err != nil {
		return nil, nil, nil, err
	}

	return resp.PublicKey, resp.PrivateKey, resp.Claims, nil
}
577341
func DumpRSAPEMKeyPair(public, private []byte) ([]byte, error) {
	// Do some validation first.  These don't have to be a matched pair,
	//   but they do have to be PEM, and they have to be a public and
	//	 private key, respectively
	if _, err := RSAPublicKeyFromPEM(public); err != nil {
		return nil, err
	}

	if _, err := RSAPrivateKeyFromPEM(private); err != nil {
		return nil, err
	}

	var out bytes.Buffer
	if _, err := out.Write(private); err != nil {
		return nil, err
	}
	if _, err := out.Write(public); err != nil {
		return nil, err
	}

	return out.Bytes(), nil
}
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
}
284346
func GenerateKeypair(passphrase string) (*PrivateKey, error) {
	pub, priv, err := box.GenerateKey(crypto_rand.Reader)
	if err != nil {
		return nil, err
	}
	k := &PrivateKey{
		PublicKey: PublicKey{
			CreationTime: time.Now(),
			PubKeyAlgo:   PubKeyNaCl,
			PublicKey:    *pub,
			Identity:     &xcpb.Identity{},
		},
		Encrypted:  true,
		privateKey: *priv,
	}
	err = k.Encrypt(passphrase)
	return k, err
}
663638
func (client *Client) CreateKeyPair(args *CreateKeyPairArgs) (resp *CreateKeyPairResponse, err error) {
	response := CreateKeyPairResponse{}
	err = client.Invoke("CreateKeyPair", args, &response)
	if err != nil {
		return nil, err
	}
	return &response, err
}
580844
func MakeRandomTLFEphemeralKeys() (
	TLFEphemeralPublicKey, TLFEphemeralPrivateKey, error) {
	keyPair, err := libkb.GenerateNaclDHKeyPair()
	if err != nil {
		return TLFEphemeralPublicKey{}, TLFEphemeralPrivateKey{},
			errors.WithStack(err)
	}

	ePubKey := MakeTLFEphemeralPublicKey(keyPair.Public)
	ePrivKey := MakeTLFEphemeralPrivateKey(*keyPair.Private)
	return ePubKey, ePrivKey, nil
}
714371
func generateKeyPairs() ([]byte, []byte, error) {
	str := util.RandomHexString()
	public, private, err := crypto.ED25519GenerateKey(str)
	return public, private, err
}
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)
}
630847
func LoadRSAKeyPair(pub, priv []byte) (public crypto.PublicKey, private crypto.PrivateKey, err error) {
	public, err = RSAPublicKeyFromPEM(pub)
	if err != nil {
		return nil, nil, err
	}

	private, err = RSAPrivateKeyFromPEM(priv)
	if err != nil {
		return nil, nil, err
	}

	return public, private, nil
}
758682
func (c *ca) NewClientCertKeyPair() (*CertKeyPair, error) {
	return newCertKeyPair(false, false, "", c.caCert.Signer, c.caCert.TLSCert)
}
933926
func (c *ClientsetCAStore) storeKeypair(name string, id string, cert *pki.Certificate, privateKey *pki.PrivateKey) error {
	var publicMaterial bytes.Buffer
	if _, err := cert.WriteTo(&publicMaterial); err != nil {
		return err
	}

	var privateMaterial bytes.Buffer
	if _, err := privateKey.WriteTo(&privateMaterial); err != nil {
		return err
	}

	item := &kops.KeysetItem{
		Id:              id,
		PublicMaterial:  publicMaterial.Bytes(),
		PrivateMaterial: privateMaterial.Bytes(),
	}
	return c.addKey(name, kops.SecretTypeKeypair, item)
}
407107
func CreateCACSR(uri CertURI, privateKey crypto.Signer) (string, error) {
	ext, err := CreateCAExtension()
	if err != nil {
		return "", err
	}

	return CreateCSR(uri, privateKey, ext)
}
686805
func newRsaKeyPair(config CreateKeyPairConfig) (KeyPair, error) {
	if config.Bits == 0 {
		config.Bits = defaultRsaBits
	}

	privateKey, err := rsa.GenerateKey(rand.Reader, config.Bits)
	if err != nil {
		return KeyPair{}, err
	}

	sshPublicKey, err := gossh.NewPublicKey(&privateKey.PublicKey)
	if err != nil {
		return KeyPair{}, err
	}

	privatePemBlock, err := rawPemBlock(&pem.Block{
		Type:    "RSA PRIVATE KEY",
		Headers: nil,
		Bytes:   x509.MarshalPKCS1PrivateKey(privateKey),
	})
	if err != nil {
		return KeyPair{}, err
	}

	return KeyPair{
		PrivateKeyPemBlock:          privatePemBlock,
		PublicKeyAuthorizedKeysLine: authorizedKeysLine(sshPublicKey, config.Comment),
		Comment:                     config.Comment,
	}, nil
}
1365624
func (c *NodeupModelContext) BuildCertificatePairTask(ctx *fi.ModelBuilderContext, key, path, filename string) error {
	certificateName := filepath.Join(path, filename+".pem")
	keyName := filepath.Join(path, filename+"-key.pem")

	if err := c.BuildCertificateTask(ctx, key, certificateName); err != nil {
		return err
	}

	return c.BuildPrivateKeyTask(ctx, key, keyName)
}
478434
func keyFromSub(sub *subscription) string {
	var _rkey [1024]byte
	var key []byte

	if sub.queue != nil {
		// Just make the key subject spc group, e.g. 'foo bar'
		key = _rkey[:0]
		key = append(key, sub.subject...)
		key = append(key, byte(' '))
		key = append(key, sub.queue...)
	} else {
		key = sub.subject
	}
	return string(key)
}