当前位置: 首页>>代码示例>>Golang>>正文


Golang pem.Decode函数代码示例

本文整理汇总了Golang中encoding/pem.Decode函数的典型用法代码示例。如果您正苦于以下问题:Golang Decode函数的具体用法?Golang Decode怎么用?Golang Decode使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了Decode函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: LoadCertsKeys

func LoadCertsKeys(uname string, upass []byte) (ca []byte, ee []byte, pkey []byte, err error) {
	user_dir := common.GetConfDir(uname)
	cafs, err := ioutil.ReadFile(filepath.Join(user_dir, "ca.cert"))
	if err != nil {
		return nil, nil, nil, err
	}
	ca, err = passcrypto.DecryptMeBase32(string(cafs), upass)
	if err != nil {
		return nil, nil, nil, err
	}
	ee_pem, err := ioutil.ReadFile(filepath.Join(user_dir, "ee.cert"))
	if err != nil {
		return nil, nil, nil, err
	}
	ee_blk, _ := pem.Decode(ee_pem)
	ee = ee_blk.Bytes
	pkeyfs, err := ioutil.ReadFile(filepath.Join(user_dir, "ee.key"))
	if err != nil {
		return nil, nil, nil, err
	}
	pkey_pem, _ := pem.Decode(pkeyfs)
	pkey, err = x509.DecryptPEMBlock(pkey_pem, upass)
	if err != nil {
		return nil, nil, nil, err
	}
	return
}
开发者ID:hujun-open,项目名称:manpass,代码行数:27,代码来源:transport.go

示例2: init

func init() {
	var err error
	var pemBytes []byte
	var key crypto.Signer
	var p *pem.Block

	s, err = NewServerFromFile(certFile, keyFile, caFile, addr, os.Stdout)
	if err != nil {
		log.Fatal(err)
	}

	if pemBytes, err = ioutil.ReadFile(rsaPrivKey); err != nil {
		log.Fatal(err)
	}
	p, _ = pem.Decode(pemBytes)
	if key, err = x509.ParsePKCS1PrivateKey(p.Bytes); err != nil {
		log.Fatal(err)
	}
	s.RegisterKey(key)

	if pemBytes, err = ioutil.ReadFile(ecdsaPrivKey); err != nil {
		log.Fatal(err)
	}
	p, _ = pem.Decode(pemBytes)
	if key, err = x509.ParseECPrivateKey(p.Bytes); err != nil {
		log.Fatal(err)
	}
	s.RegisterKey(key)
}
开发者ID:AnonSuite,项目名称:gokeyless,代码行数:29,代码来源:server_test.go

示例3: TestExportKeysByID

func TestExportKeysByID(t *testing.T) {
	setUp(t)
	tempBaseDir, err := ioutil.TempDir("", "notary-test-")
	require.NoError(t, err)
	defer os.RemoveAll(tempBaseDir)
	output, err := ioutil.TempFile("", "notary-test-import-")
	require.NoError(t, err)
	defer os.RemoveAll(output.Name())
	k := &keyCommander{
		configGetter: func() (*viper.Viper, error) {
			v := viper.New()
			v.SetDefault("trust_dir", tempBaseDir)
			return v, nil
		},
	}
	k.outFile = output.Name()
	err = output.Close() // close so export can open
	require.NoError(t, err)
	k.exportKeyIDs = []string{"one", "three"}

	b := &pem.Block{}
	b.Bytes = make([]byte, 1000)
	rand.Read(b.Bytes)

	b2 := &pem.Block{}
	b2.Bytes = make([]byte, 1000)
	rand.Read(b2.Bytes)

	c := &pem.Block{}
	c.Bytes = make([]byte, 1000)
	rand.Read(c.Bytes)

	bBytes := pem.EncodeToMemory(b)
	b2Bytes := pem.EncodeToMemory(b2)
	cBytes := pem.EncodeToMemory(c)

	fileStore, err := store.NewPrivateKeyFileStorage(tempBaseDir, notary.KeyExtension)
	require.NoError(t, err)
	err = fileStore.Set("one", bBytes)
	require.NoError(t, err)
	err = fileStore.Set("two", b2Bytes)
	require.NoError(t, err)
	err = fileStore.Set("three", cBytes)
	require.NoError(t, err)

	err = k.exportKeys(&cobra.Command{}, nil)
	require.NoError(t, err)

	outRes, err := ioutil.ReadFile(k.outFile)
	require.NoError(t, err)

	block, rest := pem.Decode(outRes)
	require.Equal(t, b.Bytes, block.Bytes)
	require.Equal(t, "one", block.Headers["path"])

	block, rest = pem.Decode(rest)
	require.Equal(t, c.Bytes, block.Bytes)
	require.Equal(t, "three", block.Headers["path"])
	require.Len(t, rest, 0)
}
开发者ID:jfrazelle,项目名称:notary,代码行数:60,代码来源:keys_test.go

示例4: importPem

// import (decode + decrypt) PEM block which must match one of the given types
func importPem(pemData []byte, prompt PasswordPrompt, types ...string) (*pem.Block, error) {
	block, pemData := pem.Decode(pemData)
	block2, _ := pem.Decode(pemData)
	if nil == block || nil != block2 {
		return nil, NotASinglePemBlock
	}

	{
		// check pem type
		validType := false
		for _, t := range types {
			if t == block.Type {
				validType = true
				break
			}
		}
		if !validType {
			return nil, UnexpectedPemBlock
		}
	}

	if err := utils.DecryptPemBlock(block, prompt); nil != err {
		return nil, err
	}
	return block, nil
}
开发者ID:NeuralSpaz,项目名称:go-acme-client,代码行数:27,代码来源:export.go

示例5: main

func main() {
	random, _ := os.Open("/dev/urandom", os.O_RDONLY, 0)
	pembytes := readEntireFile("/home/kris/SSL/gr0g.crt")
	cert, _ := pem.Decode(pembytes)
	keybytes := readEntireFile("/home/kris/SSL/gr0g.key")
	pk, _ := pem.Decode(keybytes)

	privatekey, _ := x509.ParsePKCS1PrivateKey(pk.Bytes)

	config := new(tls.Config)
	config.Certificates = make([]tls.Certificate, 1)
	config.Certificates[0].Certificate = [][]byte{cert.Bytes}
	config.Certificates[0].PrivateKey = privatekey
	config.Rand = random
	//config.RootCAs = caset
	config.Time = time.Seconds
	listener, err := tls.Listen("tcp", "0.0.0.0:8443", config)

	fmt.Printf("%s\n", err)
	for {
		conn, _ := listener.Accept()
		go func() {
			for {
				buf := make([]byte, 1024)
				_, err := conn.Read(buf)
				if err != nil {
					return
				}
				fmt.Printf("%s", buf)
			}
		}()
	}
}
开发者ID:gr0gmint,项目名称:gocon,代码行数:33,代码来源:sslserver.go

示例6: 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

示例7: ParseAndEncode

// ParseAndEncode takes key, certificate, and optional password
// as []byte and parses them to get a suitable format to encode them
func ParseAndEncode(key, cert, password []byte) string {
	var file string
	certBlock, _ := pem.Decode(cert)
	certBytes := certBlock.Bytes
	certificate, err := x509.ParseCertificate(certBytes)
	if err != nil {
		return file
	}

	block, _ := pem.Decode(key)
	privKey := block.Bytes
	if block.Type == "RSA PRIVATE KEY" {
		pkcsKey, err := x509.ParsePKCS1PrivateKey(privKey)
		if err != nil {
			return file
		}
		file = Encode(pkcsKey, certificate, password)
	} else if block.Type == "EC PRIVATE KEY" {
		ecKey, err := x509.ParseECPrivateKey(privKey)
		if err != nil {
			return file
		}
		file = Encode(ecKey, certificate, password)
	}

	return file
}
开发者ID:haneric21,项目名称:cfssl,代码行数:29,代码来源:pkcs12.go

示例8: TestCRLCreation

func TestCRLCreation(t *testing.T) {
	block, _ := pem.Decode([]byte(pemPrivateKey))
	priv, _ := ParsePKCS1PrivateKey(block.Bytes)
	block, _ = pem.Decode([]byte(pemCertificate))
	cert, _ := ParseCertificate(block.Bytes)

	now := time.Unix(1000, 0)
	expiry := time.Unix(10000, 0)

	revokedCerts := []pkix.RevokedCertificate{
		{
			SerialNumber:   big.NewInt(1),
			RevocationTime: now,
		},
		{
			SerialNumber:   big.NewInt(42),
			RevocationTime: now,
		},
	}

	crlBytes, err := cert.CreateCRL(rand.Reader, priv, revokedCerts, now, expiry)
	if err != nil {
		t.Errorf("error creating CRL: %s", err)
	}

	_, err = ParseDERCRL(crlBytes)
	if err != nil {
		t.Errorf("error reparsing CRL: %s", err)
	}
}
开发者ID:Ericean,项目名称:go,代码行数:30,代码来源:x509_test.go

示例9: init

func init() {
	var err error
	var pemBytes []byte
	var pub crypto.PublicKey
	var p *pem.Block

	if client, err = NewClient(certFile, keyFile, caFile, ioutil.Discard); err != nil {
		log.Fatal(err)
	}

	if pemBytes, err = ioutil.ReadFile(rsaPubKey); err != nil {
		log.Fatal(err)
	}
	p, _ = pem.Decode(pemBytes)
	if pub, err = x509.ParsePKIXPublicKey(p.Bytes); err != nil {
		log.Fatal(err)
	}
	if rsaKey, err = client.RegisterPublicKey(server, pub); err != nil {
		log.Fatal(err)
	}

	if pemBytes, err = ioutil.ReadFile(ecdsaPubKey); err != nil {
		log.Fatal(err)
	}
	p, _ = pem.Decode(pemBytes)
	if pub, err = x509.ParsePKIXPublicKey(p.Bytes); err != nil {
		log.Fatal(err)
	}
	if ecdsaKey, err = client.RegisterPublicKey(server, pub); err != nil {
		log.Fatal(err)
	}
}
开发者ID:AnonSuite,项目名称:gokeyless,代码行数:32,代码来源:client_test.go

示例10: GetCA

func GetCA(pkiroot string) (*x509.Certificate, *rsa.PrivateKey, error) {
	caKeyBytes, err := ioutil.ReadFile(filepath.Join(pkiroot, "private", "ca.key"))
	if err != nil {
		return nil, nil, fmt.Errorf("read ca private key: %v", err)
	}
	p, _ := pem.Decode(caKeyBytes)
	if p == nil {
		return nil, nil, fmt.Errorf("pem decode did not found pem encoded ca private key")
	}
	caKey, err := x509.ParsePKCS1PrivateKey(p.Bytes)
	if err != nil {
		return nil, nil, fmt.Errorf("parse ca private key: %v", err)
	}

	caCrtBytes, err := ioutil.ReadFile(filepath.Join(pkiroot, "ca.crt"))
	if err != nil {
		return nil, nil, fmt.Errorf("read ca crt: %v", err)
	}
	p, _ = pem.Decode(caCrtBytes)
	if p == nil {
		return nil, nil, fmt.Errorf("pem decode did not found pem encoded ca cert")
	}
	caCrt, err := x509.ParseCertificate(p.Bytes)
	if err != nil {
		return nil, nil, fmt.Errorf("parse ca crt: %v", err)
	}

	return caCrt, caKey, nil
}
开发者ID:postfix,项目名称:easypki,代码行数:29,代码来源:easyca.go

示例11: LoadCertKeyFromEncPkg

func LoadCertKeyFromEncPkg(encpkg []byte, passwd string) (*CertKey, error) {
	blk, _ := pem.Decode(encpkg)
	if blk == nil {
		return nil, errors.New("Invalid PEM data")
	}
	if blk.Type != pkgTypeStr {
		return nil, errors.New("PEM type is not " + pkgTypeStr)
	}
	decrypted_pem, err := x509.DecryptPEMBlock(blk, []byte(passwd))
	if err != nil {
		return nil, err
	}
	key_pem, rest := pem.Decode(decrypted_pem)
	if blk == nil {
		return nil, errors.New("decrypted content is not PEM")
	}
	cert_pem, _ := pem.Decode(rest)
	if blk == nil {
		return nil, errors.New("Can't find the cert PEM")
	}
	if _, ok := supportedKeyTypes[key_pem.Type]; !ok {
		return nil, errors.New("Unsupported Key types")
	}
	if cert_pem.Type != "CERTIFICATE" {
		return nil, errors.New("Can't find certificate in decrypted PEM data")
	}
	var ck CertKey
	switch key_pem.Type {
	case "RSA PRIVATE KEY":
		rsack := new(RSACertKey)
		priv_key, err := x509.ParsePKCS1PrivateKey(key_pem.Bytes)
		if err != nil {
			return nil, err
		}
		rsack.key = priv_key
		cert, err := x509.ParseCertificates(cert_pem.Bytes)
		if err != nil {
			return nil, err
		}
		rsack.cert = *cert[0]
		ck = rsack
		return &ck, nil
	case "EC PRIVATE KEY":
		ecck := new(ECCertKey)
		priv_key, err := x509.ParseECPrivateKey(key_pem.Bytes)
		if err != nil {
			return nil, err
		}
		ecck.key = priv_key
		cert, err := x509.ParseCertificates(cert_pem.Bytes)
		if err != nil {
			return nil, err
		}
		ecck.cert = *cert[0]
		ck = ecck
		return &ck, nil
	}
	return nil, errors.New("Unussal error, you shouldn't see this")

}
开发者ID:hujun-open,项目名称:manpass,代码行数:60,代码来源:pki.go

示例12: newCertPool

// newCertPool creates a new x509.CertPool by loading the
// PEM blocks from loadFn(path) and adding them to a CertPool.
func newCertPool(path string, caUpgradeCN string, loadFn func(path string) (pemBlocks map[string][]byte, err error)) (*x509.CertPool, error) {
	pemBlocks, err := loadFn(path)
	if err != nil {
		return nil, err
	}

	if len(pemBlocks) == 0 {
		return nil, nil
	}

	pool := x509.NewCertPool()
	for _, pemBlock := range pemBlocks {
		for p, rest := pem.Decode(pemBlock); p != nil; p, rest = pem.Decode(rest) {
			cert, err := x509.ParseCertificate(p.Bytes)
			if err != nil {
				return nil, err
			}
			upgradeCACertificate(cert, caUpgradeCN)
			pool.AddCert(cert)
		}
	}

	log.Printf("[INFO] cert: Load client CA certs from %s", path)
	return pool, nil
}
开发者ID:hilerchyn,项目名称:fabio,代码行数:27,代码来源:load.go

示例13: TestGenerateMemCert

func TestGenerateMemCert(t *testing.T) {
	if testing.Short() {
		t.Skip("skipping cert generation in short mode")
	}
	cert, key, err := GenerateMemCert(false)
	if err != nil {
		t.Error(err)
		return
	}
	if cert == nil {
		t.Error("GenerateMemCert returned a nil cert")
		return
	}
	if key == nil {
		t.Error("GenerateMemCert returned a nil key")
		return
	}
	block, rest := pem.Decode(cert)
	if len(rest) != 0 {
		t.Errorf("GenerateMemCert returned a cert with trailing content: %q", string(rest))
	}
	if block.Type != "CERTIFICATE" {
		t.Errorf("GenerateMemCert returned a cert with Type %q not \"CERTIFICATE\"", block.Type)
	}
	block, rest = pem.Decode(key)
	if len(rest) != 0 {
		t.Errorf("GenerateMemCert returned a key with trailing content: %q", string(rest))
	}
	if block.Type != "RSA PRIVATE KEY" {
		t.Errorf("GenerateMemCert returned a cert with Type %q not \"RSA PRIVATE KEY\"", block.Type)
	}
}
开发者ID:vahe,项目名称:lxd,代码行数:32,代码来源:cert_test.go

示例14: TestEncryptedKeyImportSuccess

// path and encrypted key should succeed, tests gun inference from path as well
func TestEncryptedKeyImportSuccess(t *testing.T) {
	s := NewTestImportStore()

	privKey, err := utils.GenerateECDSAKey(rand.Reader)
	originalKey := privKey.Private()
	require.NoError(t, err)

	pemBytes, err := utils.EncryptPrivateKey(privKey, data.CanonicalSnapshotRole, "somegun", cannedPassphrase)
	require.NoError(t, err)

	b, _ := pem.Decode(pemBytes)
	b.Headers["path"] = privKey.ID()
	pemBytes = pem.EncodeToMemory(b)

	in := bytes.NewBuffer(pemBytes)

	_ = ImportKeys(in, []Importer{s}, "", "", passphraseRetriever)
	require.Len(t, s.data, 1)

	keyBytes := s.data[privKey.ID()]

	bFinal, bRest := pem.Decode(keyBytes)
	require.Equal(t, "somegun", bFinal.Headers["gun"])
	require.Len(t, bRest, 0)

	// we should fail to parse it without the passphrase
	privKey, err = utils.ParsePEMPrivateKey(keyBytes, "")
	require.Equal(t, err, errors.New("could not decrypt private key"))
	require.Nil(t, privKey)

	// we should succeed to parse it with the passphrase
	privKey, err = utils.ParsePEMPrivateKey(keyBytes, cannedPassphrase)
	require.NoError(t, err)
	require.Equal(t, originalKey, privKey.Private())
}
开发者ID:jfrazelle,项目名称:notary,代码行数:36,代码来源:keys_test.go

示例15: TestWriteCerts

func TestWriteCerts(t *testing.T) {
	dir, err := ioutil.TempDir("", "stenocerts")
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(dir)
	certFile, keyFile := filepath.Join(dir, "cert.pem"), filepath.Join(dir, "key.pem")
	if err := WriteNewCerts(certFile, keyFile, true); err != nil {
		t.Errorf("unable to generate certs files: %v", err)
	}
	// Test cert file
	if certBytes, err := ioutil.ReadFile(certFile); err != nil {
		t.Errorf("could not read cert file: %v", err)
	} else if block, _ := pem.Decode(certBytes); block == nil {
		t.Errorf("could not get cert pem block: %v", err)
	} else if _, err := x509.ParseCertificate(block.Bytes); err != nil {
		t.Errorf("could not parse cert: %v", err)
	}
	// Test key file
	if keyBytes, err := ioutil.ReadFile(keyFile); err != nil {
		t.Errorf("could not read key file: %v", err)
	} else if block, _ := pem.Decode(keyBytes); block == nil {
		t.Errorf("could not get key pem block: %v", err)
	} else if _, err := x509.ParsePKCS1PrivateKey(block.Bytes); err != nil {
		t.Errorf("could not parse key: %v", err)
	}
}
开发者ID:nizq,项目名称:stenographer,代码行数:27,代码来源:certs_test.go


注:本文中的encoding/pem.Decode函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。