// importRootCert imports the base64 encoded public certificate corresponding to the root key
// returns empty slice if path is empty
337007
func importRootCert(certFilePath string) ([]data.PublicKey, error) {
	publicKeys := make([]data.PublicKey, 0, 1)

	if certFilePath == "" {
		return publicKeys, nil
	}

	// read certificate from file
	certPEM, err := ioutil.ReadFile(certFilePath)
	if err != nil {
		return nil, fmt.Errorf("error reading certificate file: %v", err)
	}
	block, _ := pem.Decode([]byte(certPEM))
	if block == nil {
		return nil, fmt.Errorf("the provided file does not contain a valid PEM certificate %v", err)
	}

	// convert the file to data.PublicKey
	cert, err := x509.ParseCertificate(block.Bytes)
	if err != nil {
		return nil, fmt.Errorf("Parsing certificate PEM bytes to x509 certificate: %v", err)
	}
	publicKeys = append(publicKeys, tufutils.CertToKey(cert))

	return publicKeys, nil
}
102974
func (g *GPG) ImportPublicKey(ctx context.Context, buf []byte) error {
	el, err := openpgp.ReadArmoredKeyRing(bytes.NewReader(buf))
	if err != nil {
		return err
	}
	g.pubring = append(g.pubring, el...)
	return nil
}
74836
func importPathFromPath(root, basePath string) string {
	vendorTest := filepath.Join(basePath, "vendor")
	if len(root) > len(vendorTest) && root[:len(vendorTest)] == vendorTest {
		return filepath.ToSlash(root[len(vendorTest)+1:])
	}
	for _, gopath := range filepath.SplitList(build.Default.GOPATH) {
		srcPath := filepath.Join(gopath, "src")
		if strings.HasPrefix(root, srcPath) {
			return filepath.ToSlash(root[len(srcPath)+1:])
		}
	}

	srcPath := filepath.Join(build.Default.GOROOT, "src", "pkg")
	if strings.HasPrefix(root, srcPath) {
		utils.Logger.Warn("Code path should be in GOPATH, but is in GOROOT:", "path", root)
		return filepath.ToSlash(root[len(srcPath)+1:])
	}

	utils.Logger.Error("Unexpected! Code path is not in GOPATH:", "path", root)
	return ""
}
1190154
func isUnderRootImportPath(rootImportPath, path string) bool {
	return rootImportPath != "" && util.PathHasPrefix(path, rootImportPath)
}
765422
func validRootIntCerts(allIntCerts map[string][]*x509.Certificate) map[string][]*x509.Certificate {
	validIntCerts := make(map[string][]*x509.Certificate)

	// Go through every leaf cert ID, and build its valid intermediate certificate list
	for leafID, intCertList := range allIntCerts {
		for _, intCert := range intCertList {
			if err := utils.ValidateCertificate(intCert, true); err != nil {
				continue
			}
			validIntCerts[leafID] = append(validIntCerts[leafID], intCert)
		}

	}
	return validIntCerts
}
744553
func GetLocalRootCA(paths CertPaths) (RootCA, error) {
	// Check if we have a Certificate file
	cert, err := ioutil.ReadFile(paths.Cert)
	if err != nil {
		if os.IsNotExist(err) {
			err = ErrNoLocalRootCA
		}

		return RootCA{}, err
	}
	signingCert := cert

	key, err := ioutil.ReadFile(paths.Key)
	if err != nil {
		if !os.IsNotExist(err) {
			return RootCA{}, err
		}
		// There may not be a local key. It's okay to pass in a nil
		// key. We'll get a root CA without a signer.
		key = nil
		signingCert = nil
	}

	return NewRootCA(cert, signingCert, key, DefaultNodeCertExpiration, nil)
}
326899
func LoadCert(location string) (cert []byte, err error) {
	cert, err = ioutil.ReadFile(filepath.Clean(location + "/server.cert"))
	if err != nil {
		return
	}
	return
}
201354
func loadTree(root string) (*importTree, error) {
	var f fileLoaderFunc

	// HCL2 experiment is currently activated at build time via the linker.
	// See the comment on this variable for more information.
	if enableHCL2Experiment == "" {
		// Main-line behavior: always use the original HCL parser
		switch ext(root) {
		case ".tf", ".tf.json":
			f = loadFileHcl
		default:
		}
	} else {
		// Experimental behavior: use the HCL2 parser if the opt-in comment
		// is present.
		switch ext(root) {
		case ".tf":
			// We need to sniff the file for the opt-in comment line to decide
			// if the file is participating in the HCL2 experiment.
			cf, err := os.Open(root)
			if err != nil {
				return nil, err
			}
			sc := bufio.NewScanner(cf)
			for sc.Scan() {
				if sc.Text() == "#terraform:hcl2" {
					f = globalHCL2Loader.loadFile
				}
			}
			if f == nil {
				f = loadFileHcl
			}
		case ".tf.json":
			f = loadFileHcl
		default:
		}
	}

	if f == nil {
		return nil, fmt.Errorf(
			"%s: unknown configuration format. Use '.tf' or '.tf.json' extension",
			root)
	}

	c, imps, err := f(root)
	if err != nil {
		return nil, err
	}

	children := make([]*importTree, len(imps))
	for i, imp := range imps {
		t, err := loadTree(imp)
		if err != nil {
			return nil, err
		}

		children[i] = t
	}

	return &importTree{
		Path:     root,
		Raw:      c,
		Children: children,
	}, nil
}
1210663
func GetRootPath() string {
	sysPath := config.GetPath(confPeerFileSystemPath)
	return filepath.Join(sysPath, confLedgersData)
}
1027049
func LoadClientCertificate(certFile string, keyFile string) (*tls.Certificate, error) {
	if certFile != "" && keyFile != "" {
		cert, err := tls.LoadX509KeyPair(certFile, keyFile)
		if err != nil {
			log.Critical("Unable to read client certificate from file: %s or key from file: %s", certFile, keyFile)
			return nil, err
		}
		log.Debug("Client certificate loaded ")
		return &cert, nil
	}
	return nil, nil
}
1122006
func (p *ParsedCertBundle) GetCertificatePath() []*CertBlock {
	var certPath []*CertBlock

	certPath = append(certPath, &CertBlock{
		Certificate: p.Certificate,
		Bytes:       p.CertificateBytes,
	})

	if len(p.CAChain) > 0 {
		// Root CA puts itself in the chain
		if p.CAChain[0].Certificate.SerialNumber != p.Certificate.SerialNumber {
			certPath = append(certPath, p.CAChain...)
		}
	}

	return certPath
}
851145
func NewRootCA(rootCertBytes, signCertBytes, signKeyBytes []byte, certExpiry time.Duration, intermediates []byte) (RootCA, error) {
	// Parse all the certificates in the cert bundle
	parsedCerts, err := helpers.ParseCertificatesPEM(rootCertBytes)
	if err != nil {
		return RootCA{}, errors.Wrap(err, "invalid root certificates")
	}
	// Check to see if we have at least one valid cert
	if len(parsedCerts) < 1 {
		return RootCA{}, errors.New("no valid root CA certificates found")
	}

	// Create a Pool with all of the certificates found
	pool := x509.NewCertPool()
	for _, cert := range parsedCerts {
		if err := validateSignatureAlgorithm(cert); err != nil {
			return RootCA{}, err
		}
		// Check to see if all of the certificates are valid, self-signed root CA certs
		selfpool := x509.NewCertPool()
		selfpool.AddCert(cert)
		if _, err := cert.Verify(x509.VerifyOptions{Roots: selfpool}); err != nil {
			return RootCA{}, errors.Wrap(err, "error while validating Root CA Certificate")
		}
		pool.AddCert(cert)
	}

	// Calculate the digest for our Root CA bundle
	digest := digest.FromBytes(rootCertBytes)

	// The intermediates supplied must be able to chain up to the root certificates, so that when they are appended to
	// a leaf certificate, the leaf certificate can be validated through the intermediates to the root certificates.
	var intermediatePool *x509.CertPool
	var parsedIntermediates []*x509.Certificate
	if len(intermediates) > 0 {
		parsedIntermediates, _, err = ValidateCertChain(pool, intermediates, false)
		if err != nil {
			return RootCA{}, errors.Wrap(err, "invalid intermediate chain")
		}
		intermediatePool = x509.NewCertPool()
		for _, cert := range parsedIntermediates {
			intermediatePool.AddCert(cert)
		}
	}

	var localSigner *LocalSigner
	if len(signKeyBytes) != 0 || len(signCertBytes) != 0 {
		localSigner, err = newLocalSigner(signKeyBytes, signCertBytes, certExpiry, pool, intermediatePool)
		if err != nil {
			return RootCA{}, err
		}

		// If a signer is provided and there are intermediates, then either the first intermediate would be the signer CA
		// certificate (in which case it'd have the same subject and public key), or it would be a cross-signed
		// intermediate with the same subject and public key as our signing CA certificate (which could be either an
		// intermediate cert or a self-signed root cert).
		if len(parsedIntermediates) > 0 && (!bytes.Equal(parsedIntermediates[0].RawSubject, localSigner.parsedCert.RawSubject) ||
			!bytes.Equal(parsedIntermediates[0].RawSubjectPublicKeyInfo, localSigner.parsedCert.RawSubjectPublicKeyInfo)) {
			return RootCA{}, errors.New(
				"invalid intermediate chain - the first intermediate must have the same subject and public key as the signing cert")
		}
	}

	return RootCA{signer: localSigner, Intermediates: intermediates, Digest: digest, Certs: rootCertBytes, Pool: pool}, nil
}
1094257
func (c *Client) SetRootCertificate(pemFilePath string) *Client {
	rootPemData, err := ioutil.ReadFile(pemFilePath)
	if err != nil {
		c.Log.Printf("ERROR %v", err)
		return c
	}

	config, err := c.getTLSConfig()
	if err != nil {
		c.Log.Printf("ERROR %v", err)
		return c
	}
	if config.RootCAs == nil {
		config.RootCAs = x509.NewCertPool()
	}

	config.RootCAs.AppendCertsFromPEM(rootPemData)

	return c
}
1216663
func (x *XC) ImportPrivateKey(ctx context.Context, buf []byte) error {
	if err := x.secring.Import(buf); err != nil {
		return err
	}
	return x.secring.Save()
}
556395
func LoadCert(filename string) (cert *x509.Certificate, err error) {
	certPEM, err := ioutil.ReadFile(filename)
	if err != nil {
		return
	}
	block, _ := pem.Decode(certPEM)
	if block == nil {
		return nil, fmt.Errorf("No data in cert PEM file %s", filename)
	}
	cert, err = x509.ParseCertificate(block.Bytes)
	return
}
395670
func loadRootCAs() {
	caFiles := mustGetCAFiles()
	if len(caFiles) == 0 {
		return
	}
	// Get system cert pool, and empty cert pool under Windows because it is not supported
	globalRootCAs = mustGetSystemCertPool()
	// Load custom root CAs for client requests
	for _, caFile := range caFiles {
		caCert, err := ioutil.ReadFile(caFile)
		if err != nil {
			fatalIf(probe.NewError(err), "Unable to load a CA file.")
		}
		globalRootCAs.AppendCertsFromPEM(caCert)
	}
}
1272862
func SignRootMetadata(
	ctx context.Context, codec kbfscodec.Codec,
	rootMetadataSigner, writerMetadataSigner kbfscrypto.Signer,
	brmd RootMetadata) (*RootMetadataSigned, error) {
	// encode the root metadata
	buf, err := codec.Encode(brmd)
	if err != nil {
		return nil, err
	}

	var sigInfo, writerSigInfo kbfscrypto.SignatureInfo
	if mdv2, ok := brmd.(*RootMetadataV2); ok {
		// sign the root metadata
		sigInfo, err = rootMetadataSigner.Sign(ctx, buf)
		if err != nil {
			return nil, err
		}
		// Assume that writerMetadataSigner has already signed
		// mdv2 internally. If not, makeRootMetadataSigned
		// will catch it.
		writerSigInfo = mdv2.WriterMetadataSigInfo
	} else {
		// sign the root metadata -- use the KBFS signing prefix.
		sigInfo, err = rootMetadataSigner.SignForKBFS(ctx, buf)
		if err != nil {
			return nil, err
		}
		buf, err = brmd.GetSerializedWriterMetadata(codec)
		if err != nil {
			return nil, err
		}
		// sign the writer metadata
		writerSigInfo, err = writerMetadataSigner.SignForKBFS(ctx, buf)
		if err != nil {
			return nil, err
		}
	}
	return makeRootMetadataSigned(sigInfo, writerSigInfo, brmd)
}