// ReadLocalIdentity reads, parses and returns the given pub/pri key + cert from the
// key storage (dataDir).
174563
func ReadLocalIdentity(dataDir string, id IdentityID) (*Identity, error) {
	storage, err := NewProcessStorage(context.TODO(), dataDir)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	defer storage.Close()
	return storage.ReadIdentity(IdentityCurrent, id.Role)
}
649081
func ReadCertsDirectory(tlsConfig *tls.Config, directory string) error {
	fs, err := ioutil.ReadDir(directory)
	if err != nil && !os.IsNotExist(err) {
		return err
	}

	for _, f := range fs {
		if strings.HasSuffix(f.Name(), ".crt") {
			if tlsConfig.RootCAs == nil {
				systemPool, err := tlsconfig.SystemCertPool()
				if err != nil {
					return fmt.Errorf("unable to get system cert pool: %v", err)
				}
				tlsConfig.RootCAs = systemPool
			}
			logrus.Debugf("crt: %s", filepath.Join(directory, f.Name()))
			data, err := ioutil.ReadFile(filepath.Join(directory, f.Name()))
			if err != nil {
				return err
			}
			tlsConfig.RootCAs.AppendCertsFromPEM(data)
		}
		if strings.HasSuffix(f.Name(), ".cert") {
			certName := f.Name()
			keyName := certName[:len(certName)-5] + ".key"
			logrus.Debugf("cert: %s", filepath.Join(directory, f.Name()))
			if !hasFile(fs, keyName) {
				return fmt.Errorf("missing key %s for client certificate %s. Note that CA certificates should use the extension .crt", keyName, certName)
			}
			cert, err := tls.LoadX509KeyPair(filepath.Join(directory, certName), filepath.Join(directory, keyName))
			if err != nil {
				return err
			}
			tlsConfig.Certificates = append(tlsConfig.Certificates, cert)
		}
		if strings.HasSuffix(f.Name(), ".key") {
			keyName := f.Name()
			certName := keyName[:len(keyName)-4] + ".cert"
			logrus.Debugf("key: %s", filepath.Join(directory, f.Name()))
			if !hasFile(fs, certName) {
				return fmt.Errorf("Missing client certificate %s for key %s", certName, keyName)
			}
		}
	}

	return nil
}
64641
func readLocalBundle(ctx *cmd.Context, bundleFile string) (*charm.BundleData, string, error) {
	bundleData, err := charmrepo.ReadBundleFile(bundleFile)
	if err == nil {
		// If the bundle is defined with just a yaml file, the bundle
		// path is the directory that holds the file.
		return bundleData, filepath.Dir(ctx.AbsPath(bundleFile)), nil
	}

	// We may have been given a local bundle archive or exploded directory.
	bundle, _, pathErr := charmrepo.NewBundleAtPath(bundleFile)
	if charmrepo.IsInvalidPathError(pathErr) {
		return nil, "", pathErr
	}
	if pathErr != nil {
		// If the bundle files existed but we couldn't read them,
		// then return that error rather than trying to interpret
		// as a charm.
		if info, statErr := os.Stat(bundleFile); statErr == nil {
			if info.IsDir() {
				if _, ok := pathErr.(*charmrepo.NotFoundError); !ok {
					return nil, "", errors.Trace(pathErr)
				}
			}
		}

		logger.Debugf("cannot interpret as local bundle: %v", err)
		return nil, "", errors.NotValidf("local bundle %q", bundleFile)
	}
	bundleData = bundle.Data()

	// If we get to here bundleFile is a directory, in which case
	// we should use the absolute path as the bundFilePath, or it is
	// an archive, in which case we should pass the empty string.
	var bundleDir string
	if info, err := os.Stat(bundleFile); err == nil && info.IsDir() {
		bundleDir = ctx.AbsPath(bundleFile)
	}

	return bundleData, bundleDir, nil
}
541231
func (b *backend) parseIdentityDocument(ctx context.Context, s logical.Storage, pkcs7B64 string) (*identityDocument, error) {
	// Insert the header and footer for the signature to be able to pem decode it
	pkcs7B64 = fmt.Sprintf("-----BEGIN PKCS7-----\n%s\n-----END PKCS7-----", pkcs7B64)

	// Decode the PEM encoded signature
	pkcs7BER, pkcs7Rest := pem.Decode([]byte(pkcs7B64))
	if len(pkcs7Rest) != 0 {
		return nil, fmt.Errorf("failed to decode the PEM encoded PKCS#7 signature")
	}

	// Parse the signature from asn1 format into a struct
	pkcs7Data, err := pkcs7.Parse(pkcs7BER.Bytes)
	if err != nil {
		return nil, errwrap.Wrapf("failed to parse the BER encoded PKCS#7 signature: {{err}}", err)
	}

	// Get the public certificates that are used to verify the signature.
	// This returns a slice of certificates containing the default certificate
	// and all the registered certificates via 'config/certificate/<cert_name>' endpoint
	publicCerts, err := b.awsPublicCertificates(ctx, s, true)
	if err != nil {
		return nil, err
	}
	if publicCerts == nil || len(publicCerts) == 0 {
		return nil, fmt.Errorf("certificates to verify the signature are not found")
	}

	// Before calling Verify() on the PKCS#7 struct, set the certificates to be used
	// to verify the contents in the signer information.
	pkcs7Data.Certificates = publicCerts

	// Verify extracts the authenticated attributes in the PKCS#7 signature, and verifies
	// the authenticity of the content using 'dsa.PublicKey' embedded in the public certificate.
	if pkcs7Data.Verify() != nil {
		return nil, fmt.Errorf("failed to verify the signature")
	}

	// Check if the signature has content inside of it
	if len(pkcs7Data.Content) == 0 {
		return nil, fmt.Errorf("instance identity document could not be found in the signature")
	}

	var identityDoc identityDocument
	if err := jsonutil.DecodeJSON(pkcs7Data.Content, &identityDoc); err != nil {
		return nil, err
	}

	return &identityDoc, nil
}
479911
func (p *Repository) LocalEndpointIdentityRemoved(identity *identity.Identity) {
	go func() {
		scopedLog := log.WithField(logfields.Identity, identity)
		scopedLog.Debug("Removing identity references from policy cache")
		p.Mutex.RLock()
		wg := p.removeIdentityFromRuleCaches(identity)
		wg.Wait()
		p.Mutex.RUnlock()
		scopedLog.Debug("Finished cleaning policy cache")
	}()
}
1345142
func (mgr *MockCAClient) GetIdentity(id, caname string) (*api.IdentityResponse, error) {
	return nil, errors.New("not implemented")
}
5540
func (msp *bccspmsp) DeserializeIdentity(serializedID []byte) (Identity, error) {
	mspLogger.Debug("Obtaining identity")

	// We first deserialize to a SerializedIdentity to get the MSP ID
	sId := &m.SerializedIdentity{}
	err := proto.Unmarshal(serializedID, sId)
	if err != nil {
		return nil, errors.Wrap(err, "could not deserialize a SerializedIdentity")
	}

	if sId.Mspid != msp.name {
		return nil, errors.Errorf("expected MSP ID %s, received %s", msp.name, sId.Mspid)
	}

	return msp.deserializeIdentityInternal(sId.IdBytes)
}
403163
func (api *WebAccelAPI) ReadCertificate(id string) (*sacloud.WebAccelCertResponseBody, error) {
	uri := fmt.Sprintf("%s/site/%s/certificate", api.getResourceURL(), id)

	data, err := api.client.newRequest("GET", uri, nil)
	if err != nil {
		return nil, err
	}

	var res sacloud.WebAccelCertResponse
	if err := json.Unmarshal(data, &res); err != nil {
		return nil, err
	}
	return res.Certificate, nil
}
655921
func (s *SnapshotGetRepositoryService) Local(local bool) *SnapshotGetRepositoryService {
	s.local = &local
	return s
}
504441
func ReadLocalConfig(path string) (*LocalConfig, error) {
	var err error
	var config LocalConfig
	err = configUtil.UnmarshalLocalFile(path, &config)
	if os.IsNotExist(err) {
		return nil, nil
	}
	err = ValidateLocalConfig(config)
	if err != nil {
		return nil, err
	}
	return &config, nil
}
279338
func readCertFromFile(localCertFile string) ([]byte, error) {
	// Read in the cert file
	certPEM, err := ioutil.ReadFile(localCertFile)
	if err != nil {
		return nil, err
	}
	return certPEM, nil
}
1328190
func (mgr *MockMSPManager) DeserializeIdentity(serializedIdentity []byte) (msp.Identity, error) {
	return nil, nil
}
1368065
func (c *Client) GetAllIdentities(options ...RequestOption) ([]*IdentityResponse, error) {

	// Read request options
	opts, err := c.prepareOptsFromOptions(c.ctx, options...)
	if err != nil {
		return nil, err
	}

	ca, err := newCAClient(c.ctx, c.orgName)
	if err != nil {
		return nil, err
	}

	responses, err := ca.GetAllIdentities(opts.CA)
	if err != nil {
		return nil, err
	}

	return getIdentityResponses(responses), nil

}
825837
func (c *Client) GetIdentity(accessToken string) (resp GetIdentityResponse, err error) {
	if accessToken == "" {
		return resp, errors.New("/identity/get - access token must be specified")
	}

	jsonBody, err := json.Marshal(getIdentityRequest{
		ClientID:    c.clientID,
		Secret:      c.secret,
		AccessToken: accessToken,
	})

	if err != nil {
		return resp, err
	}

	err = c.Call("/identity/get", jsonBody, &resp)
	return resp, err
}
286373
func (a *awsNodeVerifier) VerifyIdentity(ctx context.Context) ([]byte, error) {
	errs := make(chan error, 0)
	doneCh := make(chan []byte, 0)

	go func() {
		encoded, err := func() ([]byte, error) {
			// @step: create a metadata client
			client := ec2metadata.New(session.New())

			// @step: get the pkcs7 signature from the metadata service
			signature, err := client.GetDynamicData("/instance-identity/pkcs7")
			if err != nil {
				return []byte{}, err
			}

			// @step: construct request for the request
			request := &Request{
				Document: []byte(signature),
			}

			return json.Marshal(request)
		}()
		if err != nil {
			errs <- err
			return
		}

		doneCh <- encoded
	}()

	select {
	case <-ctx.Done():
		return nil, ctx.Err()
	case err := <-errs:
		return nil, err
	case req := <-doneCh:
		return req, nil
	}
}
1172353
func (l *Lexer) isIdentity() bool {
	// Identity are strings not values
	r := l.Peek()
	switch {
	case r == '[':
		// This character [ is a little special
		// as it is going to look to see if the 2nd character is
		// valid identity character so ie alpha/numeric
		peek2 := l.PeekX(2)
		if len(peek2) == 2 {
			return isIdentifierFirstRune(rune(peek2[1]))
		}
		return true
	case l.isIdentityQuoteMark(r):
		// are these always identities?  or do we need
		// to also check first identifier?
		// peek2 := l.PeekX(2)
		// if len(peek2) == 2 {
		// 	return isIdentifierFirstRune(rune(peek2[1]))
		// }
		return true
	}
	return isIdentifierFirstRune(r)
}
1373353
func (dht *IpfsDHT) getLocal(key string) (*recpb.Record, error) {
	logger.Debugf("getLocal %s", key)
	rec, err := dht.getRecordFromDatastore(mkDsKey(key))
	if err != nil {
		logger.Warningf("getLocal: %s", err)
		return nil, err
	}

	// Double check the key. Can't hurt.
	if rec != nil && string(rec.GetKey()) != key {
		logger.Errorf("BUG getLocal: found a DHT record that didn't match it's key: %s != %s", rec.GetKey(), key)
		return nil, nil

	}
	return rec, nil
}