當前位置: 首頁>>代碼示例>>Golang>>正文


Golang x509.ParseCertificate函數代碼示例

本文整理匯總了Golang中crypto/x509.ParseCertificate函數的典型用法代碼示例。如果您正苦於以下問題:Golang ParseCertificate函數的具體用法?Golang ParseCertificate怎麽用?Golang ParseCertificate使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了ParseCertificate函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: init

func init() {
	// Setup the updateURL if the environment variable is set
	envApi := os.Getenv("CORE_UPDATE_URL")
	if envApi != "" {
		envUrl, err := url.Parse(envApi)
		if err != nil {
			fmt.Printf("Error: couldn't parse CORE_UPDATE_URL: %s", err.Error())
			os.Exit(-1)
		}
		updateURL = *envUrl
	}
	pool := x509.NewCertPool()

	coreosInetPemBlock, _ := pem.Decode([]byte(certs.CoreOS_Internet_Authority_pem))
	if coreosInetPemBlock == nil {
		panic("Error: No PEM data found in CoreOS_Internet_Auth")
	}

	coreosNetPemBlock, _ := pem.Decode([]byte(certs.CoreOS_Internet_Authority_pem))
	if coreosNetPemBlock == nil {
		panic("Error: No PEM data found in CoreOS_Network_Auth")
	}

	coreosInetAuthCert, err := x509.ParseCertificate(coreosInetPemBlock.Bytes)
	if err != nil {
		panic(err.Error())
	}
	coreosNetAuthCert, err := x509.ParseCertificate(coreosNetPemBlock.Bytes)
	if err != nil {
		panic(err.Error())
	}
	pool.AddCert(coreosNetAuthCert)
	pool.AddCert(coreosInetAuthCert)
	tlsTransport.TLSClientConfig = &tls.Config{RootCAs: pool}
}
開發者ID:carriercomm,項目名稱:core-admin,代碼行數:35,代碼來源:const.go

示例2: VerifyDerCert

func VerifyDerCert(der_cert []byte, der_signing_cert []byte) (bool, error) {
	roots := x509.NewCertPool()
	opts := x509.VerifyOptions{
		Roots: roots,
	}

	// Verify key
	policy_cert, err := x509.ParseCertificate(der_signing_cert)
	if err != nil {
		return false, errors.New("Signing ParseCertificate fails")
	}
	roots.AddCert(policy_cert)
	fmt.Printf("Root cert: %x\n", der_signing_cert)

	// Verify key
	cert, err := x509.ParseCertificate(der_cert)
	if err != nil {
		return false, errors.New("Cert ParseCertificate fails")
	}

	roots.AddCert(policy_cert)
	opts.Roots = roots
	chains, err := cert.Verify(opts)
	if err != nil {
		return false, errors.New("Verify fails")
	}
	if chains != nil {
		return true, nil
	} else {
		return false, nil
	}

}
開發者ID:tmroeder,項目名稱:cloudproxy,代碼行數:33,代碼來源:support.go

示例3: TestCreateCertificateCahin

func TestCreateCertificateCahin(t *testing.T) {
	ca, caPriv := createCA()
	caPub := key.PublicKey(caPriv)
	caBytes := Sign(ca, ca, caPub, caPriv)
	interCa, interCaPriv := createInterCA()
	interCaPub := key.PublicKey(interCaPriv)
	interCaBytes := Sign(interCa, ca, interCaPub, caPriv)
	client, clientPriv := createClient()
	clientPub := key.PublicKey(clientPriv)
	clientBytes := Sign(client, interCa, clientPub, interCaPriv)

	clientCert, _ := x509.ParseCertificate(clientBytes)
	ouIssuer := getPkixValue(clientCert.Issuer.Names, OU)
	if ouIssuer != "WebInterCA" {
		t.Fatalf("Wrong issuer ou wanted: WebInterCA, got: %v\n", ouIssuer)
	}
	interCert, _ := x509.ParseCertificate(interCaBytes)
	ouIssuer = getPkixValue(interCert.Issuer.Names, OU)
	if ouIssuer != "WebCA" {
		t.Fatalf("Wrong issuer ou wanted: WebCA, got: %v\n", ouIssuer)
	}
	caCert, _ := x509.ParseCertificate(caBytes)
	ouIssuer = getPkixValue(caCert.Issuer.Names, OU)
	if ouIssuer != "WebCA" {
		t.Fatalf("Wrong issuer ou wanted: WebCA, got: %v\n", ouIssuer)
	}
}
開發者ID:chrjoh,項目名稱:certificateBar,代碼行數:27,代碼來源:certhandler_test.go

示例4: TestOCSP

func TestOCSP(t *testing.T) {
	b, err := acmeutils.LoadCertificates([]byte(testOCSPCerts))
	if err != nil {
		t.Fatalf("cannot load certificates")
	}

	c0, err := x509.ParseCertificate(b[0])
	if err != nil {
		t.Fatalf("cannot parse certificate")
	}

	c1, err := x509.ParseCertificate(b[1])
	if err != nil {
		t.Fatalf("cannot parse certificate")
	}

	cl := Client{}

	res, err := cl.CheckOCSP(c0, c1, context.TODO())
	if err != nil {
		t.Fatalf("ocsp error: %v", err)
	}

	if res.Status != ocsp.Revoked {
		t.Fatalf("ocsp status should be revoked (1) but is %v", res.Status)
	}
}
開發者ID:joneskoo,項目名稱:acmetool-kapsi,代碼行數:27,代碼來源:ocsp_test.go

示例5: TestRevoke

func TestRevoke(t *testing.T) {
	cadb, storageAuthority, caConfig := setup(t)
	ca, err := NewCertificateAuthorityImpl(cadb, caConfig, caCertFile)
	test.AssertNotError(t, err, "Failed to create CA")
	if err != nil {
		return
	}
	ca.SA = storageAuthority
	ca.MaxKeySize = 4096

	csrDER, _ := hex.DecodeString(CNandSANCSRhex)
	csr, _ := x509.ParseCertificateRequest(csrDER)
	certObj, err := ca.IssueCertificate(*csr, 1, FarFuture)
	test.AssertNotError(t, err, "Failed to sign certificate")
	if err != nil {
		return
	}
	cert, err := x509.ParseCertificate(certObj.DER)
	test.AssertNotError(t, err, "Certificate failed to parse")
	serialString := core.SerialToString(cert.SerialNumber)
	err = ca.RevokeCertificate(serialString, 0)
	test.AssertNotError(t, err, "Revocation failed")

	status, err := storageAuthority.GetCertificateStatus(serialString)
	test.AssertNotError(t, err, "Failed to get cert status")

	test.AssertEquals(t, status.Status, core.OCSPStatusRevoked)
	test.Assert(t, time.Now().Sub(status.OCSPLastUpdated) > time.Second,
		fmt.Sprintf("OCSP LastUpdated was wrong: %v", status.OCSPLastUpdated))
}
開發者ID:diafygi,項目名稱:boulder,代碼行數:30,代碼來源:certificate-authority_test.go

示例6: readFiles

func readFiles(c *cli.Context) (issuer, responder, target *x509.Certificate, template ocsp.Response, pkcs11 PKCS11Config, err error) {
	// Issuer certificate
	issuerFileName := c.GlobalString("issuer")
	issuerBytes, err := ioutil.ReadFile(issuerFileName)
	if err != nil {
		return
	}

	issuer, err = x509.ParseCertificate(issuerBytes)
	if err != nil {
		return
	}

	// Responder certificate
	responderFileName := c.GlobalString("responder")
	responderBytes, err := ioutil.ReadFile(responderFileName)
	if err != nil {
		return
	}

	responder, err = x509.ParseCertificate(responderBytes)
	if err != nil {
		return
	}

	// Target certificate
	targetFileName := c.GlobalString("target")
	targetBytes, err := ioutil.ReadFile(targetFileName)
	if err != nil {
		return
	}

	target, err = x509.ParseCertificate(targetBytes)
	if err != nil {
		return
	}

	// OCSP template
	templateFileName := c.GlobalString("template")
	templateBytes, err := ioutil.ReadFile(templateFileName)
	if err != nil {
		return
	}

	err = json.Unmarshal(templateBytes, &template)
	if err != nil {
		return
	}

	// PKCS#11 config
	pkcs11FileName := c.GlobalString("pkcs11")
	pkcs11Bytes, err := ioutil.ReadFile(pkcs11FileName)
	if err != nil {
		return
	}

	err = json.Unmarshal(pkcs11Bytes, &pkcs11)
	return
}
開發者ID:patf,項目名稱:boulder,代碼行數:59,代碼來源:main.go

示例7: parseAndVerifyCertChain

func parseAndVerifyCertChain(x5c []string, roots *x509.CertPool) (leafKey libtrust.PublicKey, err error) {
	if len(x5c) == 0 {
		return nil, errors.New("empty x509 certificate chain")
	}

	// Ensure the first element is encoded correctly.
	leafCertDer, err := base64.StdEncoding.DecodeString(x5c[0])
	if err != nil {
		return nil, fmt.Errorf("unable to decode leaf certificate: %s", err)
	}

	// And that it is a valid x509 certificate.
	leafCert, err := x509.ParseCertificate(leafCertDer)
	if err != nil {
		return nil, fmt.Errorf("unable to parse leaf certificate: %s", err)
	}

	// The rest of the certificate chain are intermediate certificates.
	intermediates := x509.NewCertPool()
	for i := 1; i < len(x5c); i++ {
		intermediateCertDer, err := base64.StdEncoding.DecodeString(x5c[i])
		if err != nil {
			return nil, fmt.Errorf("unable to decode intermediate certificate: %s", err)
		}

		intermediateCert, err := x509.ParseCertificate(intermediateCertDer)
		if err != nil {
			return nil, fmt.Errorf("unable to parse intermediate certificate: %s", err)
		}

		intermediates.AddCert(intermediateCert)
	}

	verifyOpts := x509.VerifyOptions{
		Intermediates: intermediates,
		Roots:         roots,
		KeyUsages:     []x509.ExtKeyUsage{x509.ExtKeyUsageAny},
	}

	// TODO: this call returns certificate chains which we ignore for now, but
	// we should check them for revocations if we have the ability later.
	if _, err = leafCert.Verify(verifyOpts); err != nil {
		return nil, fmt.Errorf("unable to verify certificate chain: %s", err)
	}

	// Get the public key from the leaf certificate.
	leafCryptoKey, ok := leafCert.PublicKey.(crypto.PublicKey)
	if !ok {
		return nil, errors.New("unable to get leaf cert public key value")
	}

	leafKey, err = libtrust.FromCryptoPublicKey(leafCryptoKey)
	if err != nil {
		return nil, fmt.Errorf("unable to make libtrust public key from leaf certificate: %s", err)
	}

	return
}
開發者ID:HuKeping,項目名稱:distribution,代碼行數:58,代碼來源:token.go

示例8: verifyCertChain

// Verify x509 certificate chain
func (x5c X5C) verifyCertChain() (leaf *x509.Certificate, validCN bool, err error) {
	if len(x5c) == 0 || len(x5c) > 10 {
		// OpenSSL's default maximum chain length is 10
		return nil, false, fmt.Errorf("Invalid certchain length of %d\n", len(x5c))
	}

	// Parse leaf certificate
	leafCertDer, err := base64.StdEncoding.DecodeString(x5c[0])
	if err != nil {
		return nil, false, err
	}
	leafCert, err := x509.ParseCertificate(leafCertDer)
	if err != nil {
		return nil, false, err
	}

	// Verify CN
	if leafCert.Subject.CommonName == safetynetCN {
		validCN = true
	}

	// Parse and add intermediate certificates
	intermediates := x509.NewCertPool()
	for i := 1; i < len(x5c); i++ {
		intermediateCertDer, err := base64.StdEncoding.DecodeString(x5c[i])
		if err != nil {
			return leafCert, false, err
		}

		intermediateCert, err := x509.ParseCertificate(intermediateCertDer)
		if err != nil {
			return leafCert, false, err
		}
		intermediates.AddCert(intermediateCert)
	}

	// Parse and verify root cert
	roots := x509.NewCertPool()
	ok := roots.AppendCertsFromPEM([]byte(geotrustCert))
	if !ok {
		return leafCert, false, fmt.Errorf("Failed to append GEOTRUST cert\n")
	}

	// Verify leaf certificate
	storeCtx := x509.VerifyOptions{
		Intermediates: intermediates,
		Roots:         roots,
		KeyUsages:     []x509.ExtKeyUsage{x509.ExtKeyUsageAny},
	}
	_, err = leafCert.Verify(storeCtx)
	if err != nil {
		return leafCert, false, err
	}

	return leafCert, validCN, nil
}
開發者ID:Psiphon-Labs,項目名稱:psiphon-tunnel-core,代碼行數:57,代碼來源:safetyNet.go

示例9: main

func main() {
	// input config file contains initial_keyserver_auth and keyserver_addr
	// this file will be provided by keyserver admin
	if len(os.Args) != 5 {
		fmt.Printf("usage: %s cacert cert id inputcfg\n", os.Args[0])
		return
	}
	caCertFile := os.Args[1]
	certFile := os.Args[2]
	cfgF := os.Args[4]
	id, err := strconv.ParseUint(os.Args[3], 10, 64)
	if err != nil {
		log.Fatalf("Failed to convert %v to uint: %v", os.Args[3], err)
	}
	caCertPem, err := ioutil.ReadFile(caCertFile)
	if err != nil {
		log.Fatalf("Failed to read from %v: %v", caCertFile, err)
	}
	caCertBlock, _ := pem.Decode(caCertPem)
	if caCertBlock == nil {
		log.Fatalf("Failed to parse PEM: %v", string(caCertPem))
	}
	caCert, err := x509.ParseCertificate(caCertBlock.Bytes)
	if err != nil {
		log.Fatalf("Failed to parse X.509 cert: %v", err)
	}

	certPEM, err := ioutil.ReadFile(certFile)
	if err != nil {
		log.Fatalf("Failed to read from %v: %v", certFile, err)
	}

	certBlock, _ := pem.Decode(certPEM)
	if certBlock == nil {
		log.Fatalf("Failed to parse PEM: %v", string(certPEM))
	}
	cert, err := x509.ParseCertificate(certBlock.Bytes)
	if err != nil {
		log.Fatalf("Failed to parse X.509 cert: %v", err)
	}

	configReader, err := os.Open(cfgF)
	if err != nil {
		log.Fatalf("Failed to open input configuration file %v: %v", cfgF, err)
	}
	cfg := &proto.VerifierConfig{}
	err = jsonpb.Unmarshal(configReader, cfg)
	if err != nil {
		log.Fatalf("Failed to parse input configuration file %v: %v", cfgF, err)
	}

	make_config(caCert, cert, uint64(id), cfg)
}
開發者ID:yahoo,項目名稱:coname,代碼行數:53,代碼來源:main.go

示例10: loadCertFromPEM

func (m *Meta) loadCertFromPEM(path string) ([]*x509.Certificate, error) {
	pemCerts, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, err
	}

	certs := make([]*x509.Certificate, 0, 5)
	for len(pemCerts) > 0 {
		var block *pem.Block
		block, pemCerts = pem.Decode(pemCerts)
		if block == nil {
			break
		}
		if block.Type != "CERTIFICATE" || len(block.Headers) != 0 {
			continue
		}

		cert, err := x509.ParseCertificate(block.Bytes)
		if err != nil {
			return nil, err
		}

		certs = append(certs, cert)
	}

	return certs, nil
}
開發者ID:geckoboard,項目名稱:vault,代碼行數:27,代碼來源:meta.go

示例11: DetermineKeyIDFromPublicKey

func DetermineKeyIDFromPublicKey(pubk crypto.PublicKey) (string, error) {
	// Trick crypto/x509 into creating a certificate so we can grab the
	// subjectPublicKeyInfo by giving it a fake private key generating an invalid
	// signature. ParseCertificate doesn't verify the signature so this will
	// work.
	//
	// Yes, this is very hacky, but avoids having to duplicate code in crypto/x509.

	determineKeyIDFromKeyIntl(pubk, psuedoPrivateKey{})

	cc := &x509.Certificate{
		SerialNumber: big.NewInt(1),
	}
	cb, err := x509.CreateCertificate(rand.Reader, cc, cc, pubk, &psuedoPrivateKey{pubk})
	if err != nil {
		return "", err
	}

	c, err := x509.ParseCertificate(cb)
	if err != nil {
		return "", err
	}

	return determineKeyIDFromCert(c), nil
}
開發者ID:joneskoo,項目名稱:acmetool-kapsi,代碼行數:25,代碼來源:util.go

示例12: NewSignedCertificate

func NewSignedCertificate(cfg CertConfig, key *rsa.PrivateKey, caCert *x509.Certificate, caKey *rsa.PrivateKey) (*x509.Certificate, error) {
	serial, err := rand.Int(rand.Reader, new(big.Int).SetInt64(math.MaxInt64))
	if err != nil {
		return nil, err
	}

	certTmpl := x509.Certificate{
		Subject: pkix.Name{
			CommonName:   cfg.CommonName,
			Organization: caCert.Subject.Organization,
		},
		DNSNames:     cfg.AltNames.DNSNames,
		IPAddresses:  cfg.AltNames.IPs,
		SerialNumber: serial,
		NotBefore:    caCert.NotBefore,
		NotAfter:     time.Now().Add(Duration365d).UTC(),
		KeyUsage:     x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
		ExtKeyUsage:  []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth},
	}
	certDERBytes, err := x509.CreateCertificate(rand.Reader, &certTmpl, caCert, key.Public(), caKey)
	if err != nil {
		return nil, err
	}
	return x509.ParseCertificate(certDERBytes)
}
開發者ID:40a,項目名稱:bootkube,代碼行數:25,代碼來源:tlsutil.go

示例13: checkRouteCertificate

func checkRouteCertificate(r diagnosticReporter, route routes.Route) {
	r.Debug("AGL0330", fmt.Sprintf("Checking certificate for route '%s'...", route.ObjectMeta.Name))
	block, _ := pem.Decode([]byte(route.Spec.TLS.Certificate))
	//verify hostname
	if block != nil {
		cert, err := x509.ParseCertificate(block.Bytes)
		if err != nil {
			r.Error("AGL0335", err, fmt.Sprintf("Unable to parse the certificate for route '%s': %s", route.ObjectMeta.Name, err))
			return
		}
		r.Debug("AGL0340", fmt.Sprintf("Cert CommonName: '%s' Cert DNSNames: '%s'", cert.Subject.CommonName, cert.DNSNames))
		if err := cert.VerifyHostname(route.Spec.Host); err != nil {
			r.Error("AGL0345", err, fmt.Sprintf("Route '%[1]s' certficate does not include route host '%[2]s'"+routeCertMissingHostName, route.ObjectMeta.Name, route.Spec.Host))
		}
	} else {
		r.Error("AGL0350", errors.New("Unable to decode the TLS Certificate"), "Unable to decode the TLS Certificate")
	}

	//verify key matches cert
	r.Debug("AGL0355", fmt.Sprintf("Checking certificate matches key for route '%s'", route.ObjectMeta.Name))
	_, err := tls.X509KeyPair([]byte(route.Spec.TLS.Certificate), []byte(route.Spec.TLS.Key))
	if err != nil {
		r.Error("AGL0365", err, fmt.Sprintf("Route '%s' key and certificate do not match: %s.  The router will be unable to pass traffic using this route.", route.ObjectMeta.Name, err))
	}
}
開發者ID:LalatenduMohanty,項目名稱:origin,代碼行數:25,代碼來源:routes.go

示例14: parsePEMBundle

// parsePEMBundle parses a certificate bundle from top to bottom and returns
// a slice of x509 certificates. This function will error if no certificates are found.
func parsePEMBundle(bundle []byte) ([]*x509.Certificate, error) {
	var certificates []*x509.Certificate

	remaining := bundle
	for len(remaining) != 0 {
		certBlock, rem := pem.Decode(remaining)
		// Thanks golang for having me do this :[
		remaining = rem
		if certBlock == nil {
			return nil, errors.New("Could not decode certificate.")
		}

		cert, err := x509.ParseCertificate(certBlock.Bytes)
		if err != nil {
			return nil, err
		}

		certificates = append(certificates, cert)
	}

	if len(certificates) == 0 {
		return nil, errors.New("No certificates were found while parsing the bundle.")
	}

	return certificates, nil
}
開發者ID:kennwhite,項目名稱:lego,代碼行數:28,代碼來源:crypto.go

示例15: getIssuerCertificate

// getIssuerCertificate requests the issuer certificate and caches it for
// subsequent requests.
func (c *Client) getIssuerCertificate(url string) ([]byte, error) {
	logf("[INFO] acme: Requesting issuer cert from %s", url)
	if c.issuerCert != nil {
		return c.issuerCert, nil
	}

	resp, err := httpGet(url)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	issuerBytes, err := ioutil.ReadAll(limitReader(resp.Body, 1024*1024))
	if err != nil {
		return nil, err
	}

	_, err = x509.ParseCertificate(issuerBytes)
	if err != nil {
		return nil, err
	}

	c.issuerCert = issuerBytes
	return issuerBytes, err
}
開發者ID:Rudloff,項目名稱:platform,代碼行數:27,代碼來源:client.go


注:本文中的crypto/x509.ParseCertificate函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。