// SigExtractPayloadAndKID extracts the payload and KID of the key that
// was supposedly used to sign this message. A KID will only be returned
// for KB messages, and not for PGP messages
962308
func SigExtractPayloadAndKID(armored string) (payload []byte, kid keybase1.KID, sigID keybase1.SigID, err error) {
	if isPGPBundle(armored) {
		payload, sigID, err = SigExtractPGPPayload(armored)
	} else {
		payload, kid, sigID, err = SigExtractKbPayloadAndKID(armored)
	}
	return payload, kid, sigID, err
}
217851
func (c *Cert) genAndWriteKey(path string) error {
	c.Log.Infof("Generating new RSA key")
	if err := c.generateKey(); err != nil {
		return fmt.Errorf("error generating key: %v", err)
	}

	if err := c.writeKeyToFile(path); err != nil {
		return fmt.Errorf("error saving key to file '%s': %v", path, err)
	}
	c.Log.Infof("Key written to file: %s", path)

	return nil
}
601699
func (o *GetJSONWebKeyParams) WithKid(kid string) *GetJSONWebKeyParams {
	o.SetKid(kid)
	return o
}
920177
func (k *SKBKeyringFile) FindSecretKey(kids []keybase1.KID) (ret *SKB) {
	k.Lock()
	defer k.Unlock()
	for _, kid := range kids {
		if ret = k.lookupByKidLocked(kid); ret != nil {
			return
		}
	}
	return
}
721187
func (u *utils) DecryptPEMBlock(block *pem.Block, password []byte) ([]byte, error) {
	if IsPKCS8(block.Bytes) {
		return pkcs8.DecryptPEMBlock(block, password)
	} else if u.fips {
		return nil, ErrFIPSUnsupportedKeyFormat
	}

	return x509.DecryptPEMBlock(block, password)
}
298583
func LoadX509KeyPair(certFile, keyFile string) (Certificate, error) {
	certPEMBlock, err := ioutil.ReadFile(certFile)
	if err != nil {
		return Certificate{}, err
	}
	keyPEMBlock, err := ioutil.ReadFile(keyFile)
	if err != nil {
		return Certificate{}, err
	}
	return X509KeyPair(certPEMBlock, keyPEMBlock)
}
193005
func (context *Context) LoadKeyByBlob(parent *Key, blob []byte) (*Key, error) {
	var handle C.TSS_HKEY
	err := tspiError(C.Tspi_Context_LoadKeyByBlob(context.context, parent.handle, (C.UINT32)(len(blob)), (*C.BYTE)(unsafe.Pointer(&blob[0])), &handle))
	return &Key{handle: handle, context: context.context}, err
}
943906
func (ctx *Context) CookieUint64(key string, defaults ...uint64) uint64 {
	return ctx.Cookies().MustUint64(key, defaults...)
}
906049
func decryptPEMBlock(c *Client, block *pem.Block, path string, key []byte) ([]byte, error) {
	fileurl := fmt.Sprintf("cert:///%s", filepath.ToSlash(path))
	url, err := url.Parse(fileurl)
	if err != nil {
		return nil, err
	}
	credHelper, input := c.credHelperContext.GetCredentialHelper(nil, url)

	input["username"] = ""

	creds, err := credHelper.Fill(input)
	if err != nil {
		tracerx.Printf("Error filling credentials for %q: %v", fileurl, err)
		return nil, err
	}
	pass := creds["password"]
	decrypted, err := x509.DecryptPEMBlock(block, []byte(pass))
	if err != nil {
		credHelper.Reject(creds)
		return nil, err
	}
	credHelper.Approve(creds)

	// decrypted is a DER blob, but we need a PEM-encoded block.
	toEncode := &pem.Block{Type: block.Type, Headers: nil, Bytes: decrypted}
	buf := pem.EncodeToMemory(toEncode)
	return buf, nil
}
1002954
func LoadX509Signer(privateKeyPath, certPath string) (*X509Signer, error) {
	pkey, err := ioutil.ReadFile(privateKeyPath)
	if err != nil {
		return nil, err
	}
	cert, err := ioutil.ReadFile(certPath)
	if err != nil {
		return nil, err
	}
	signer := &X509Signer{
		PrivateKeyPEM:  pkey,
		CertificatePEM: cert,
	}
	if err = signer.Validate(); err != nil {
		return nil, err
	}
	return signer, nil
}
736485
func CertToKey(cert *x509.Certificate) data.PublicKey {
	block := pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw}
	pemdata := pem.EncodeToMemory(&block)

	switch cert.PublicKeyAlgorithm {
	case x509.RSA:
		return data.NewRSAx509PublicKey(pemdata)
	case x509.ECDSA:
		return data.NewECDSAx509PublicKey(pemdata)
	default:
		logrus.Debugf("Unknown key type parsed from certificate: %v", cert.PublicKeyAlgorithm)
		return nil
	}
}
881073
func (m *tokenManager) loadPrivateKey(tm *tokenManager, key []byte, kid string, deprecatedKey []byte, deprecatedKid string) (*token.PrivateKey, error) {
	if len(key) == 0 || kid == "" {
		log.Error(nil, map[string]interface{}{
			"kid":        kid,
			"key_length": len(key),
		}, "private key or its ID are not set up")
		return nil, errors.New("private key or its ID are not set up")
	}

	// Load the private key. Extract the public key from it
	rsaServiceAccountKey, err := jwt.ParseRSAPrivateKeyFromPEM(key)
	if err != nil {
		log.Error(nil, map[string]interface{}{"err": err}, "unable to parse private key")
		return nil, err
	}
	privateKey := &token.PrivateKey{KeyID: kid, Key: rsaServiceAccountKey}
	pk := &rsaServiceAccountKey.PublicKey
	tm.publicKeysMap[kid] = pk
	tm.publicKeys = append(tm.publicKeys, &token.PublicKey{KeyID: kid, Key: pk})
	log.Info(nil, map[string]interface{}{"kid": kid}, "public key added")

	// Extract public key from the deprecated key if any and add it to the manager
	if len(deprecatedKey) == 0 || deprecatedKid == "" {
		log.Debug(nil, map[string]interface{}{
			"kid":        deprecatedKid,
			"key_length": len(deprecatedKey),
		}, "no deprecated private key found")
	} else {
		rsaServiceAccountKey, err := jwt.ParseRSAPrivateKeyFromPEM(deprecatedKey)
		if err != nil {
			log.Error(nil, map[string]interface{}{"err": err}, "unable to parse deprecated private key")
			return nil, err
		}
		pk := &rsaServiceAccountKey.PublicKey
		tm.publicKeysMap[deprecatedKid] = pk
		tm.publicKeys = append(tm.publicKeys, &token.PublicKey{KeyID: deprecatedKid, Key: pk})
		log.Info(nil, map[string]interface{}{"kid": deprecatedKid}, "deprecated public key added")
	}
	return privateKey, nil
}
374083
func TryLoadCertAndKeyFromDisk(pkiPath, name string) (*x509.Certificate, crypto.Signer, error) {
	cert, err := TryLoadCertFromDisk(pkiPath, name)
	if err != nil {
		return nil, nil, errors.Wrap(err, "failed to load certificate")
	}

	key, err := TryLoadKeyFromDisk(pkiPath, name)
	if err != nil {
		return nil, nil, errors.Wrap(err, "failed to load key")
	}

	return cert, key, nil
}
1355468
func TryLoadCSRAndKeyFromDisk(pkiPath, name string) (*x509.CertificateRequest, crypto.Signer, error) {
	csrPath := pathForCSR(pkiPath, name)

	csr, err := CertificateRequestFromFile(csrPath)
	if err != nil {
		return nil, nil, errors.Wrapf(err, "couldn't load the certificate request %s", csrPath)
	}

	key, err := TryLoadKeyFromDisk(pkiPath, name)
	if err != nil {
		return nil, nil, errors.Wrap(err, "couldn't load key file")
	}

	return csr, key, nil
}
577125
func (sm *Manager) LoginExtensionByCertificate(ctx context.Context, key string) error {
	c := sm.client
	u := c.URL()
	if u.Hostname() != "sdkTunnel" {
		sc := c.Tunnel()
		c = &vim25.Client{
			Client:         sc,
			RoundTripper:   sc,
			ServiceContent: c.ServiceContent,
		}
		// When http.Transport.Proxy is used, our thumbprint checker is bypassed, resulting in:
		// "Post https://sdkTunnel:8089/sdk: x509: certificate is valid for $vcenter_hostname, not sdkTunnel"
		// The only easy way around this is to disable verification for the call to LoginExtensionByCertificate().
		// TODO: find a way to avoid disabling InsecureSkipVerify.
		c.Transport.(*http.Transport).TLSClientConfig.InsecureSkipVerify = true
	}

	req := types.LoginExtensionByCertificate{
		This:         sm.Reference(),
		ExtensionKey: key,
		Locale:       Locale,
	}

	login, err := methods.LoginExtensionByCertificate(ctx, c, &req)
	if err != nil {
		return err
	}

	// Copy the session cookie
	sm.client.Jar.SetCookies(u, c.Jar.Cookies(c.URL()))

	sm.userSession = &login.Returnval
	return nil
}
316972
func (e *PaperProvisionEngine) makeDeviceKeysWithSigner(m libkb.MetaContext, signer libkb.GenericKey) error {
	args, err := e.makeDeviceWrapArgs(m)
	if err != nil {
		return err
	}
	args.Signer = signer
	args.IsEldest = false // just to be explicit
	args.EldestKID = e.User.GetEldestKID()

	return e.makeDeviceKeys(m, args)
}
264441
func encryptPayload(vsn encryptionVersion, key []byte, msg []byte, data []byte, dst *bytes.Buffer) error {
	// Get the AES block cipher
	aesBlock, err := aes.NewCipher(key)
	if err != nil {
		return err
	}

	// Get the GCM cipher mode
	gcm, err := cipher.NewGCM(aesBlock)
	if err != nil {
		return err
	}

	// Grow the buffer to make room for everything
	offset := dst.Len()
	dst.Grow(encryptedLength(vsn, len(msg)))

	// Write the encryption version
	dst.WriteByte(byte(vsn))

	// Add a random nonce
	io.CopyN(dst, rand.Reader, nonceSize)
	afterNonce := dst.Len()

	// Ensure we are correctly padded (only version 0)
	if vsn == 0 {
		io.Copy(dst, bytes.NewReader(msg))
		pkcs7encode(dst, offset+versionSize+nonceSize, aes.BlockSize)
	}

	// Encrypt message using GCM
	slice := dst.Bytes()[offset:]
	nonce := slice[versionSize : versionSize+nonceSize]

	// Message source depends on the encryption version.
	// Version 0 uses padding, version 1 does not
	var src []byte
	if vsn == 0 {
		src = slice[versionSize+nonceSize:]
	} else {
		src = msg
	}
	out := gcm.Seal(nil, nonce, src, data)

	// Truncate the plaintext, and write the cipher text
	dst.Truncate(afterNonce)
	dst.Write(out)
	return nil
}