• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang pem.Decode函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: LoadKeyFromPEMFile

func LoadKeyFromPEMFile(publicKeyFilePath, privateKeyFilePath string, ParseKey func([]byte, []byte) (Key, error)) (Key, error) {

	//TODO 断言如果入参为"" ,则直接报错

	publicKeyFilePath = strings.TrimSpace(publicKeyFilePath)

	pukBytes, err := ioutil.ReadFile(publicKeyFilePath)
	if err != nil {
		return nil, err
	}

	puk, _ := pem.Decode(pukBytes)
	if puk == nil {
		return nil, errors.New("publicKey is not pem formate")
	}

	privateKeyFilePath = strings.TrimSpace(privateKeyFilePath)

	prkBytes, err := ioutil.ReadFile(privateKeyFilePath)
	if err != nil {
		return nil, err
	}

	prk, _ := pem.Decode(prkBytes)
	if prk == nil {
		return nil, errors.New("privateKey is not pem formate")
	}

	return ParseKey(puk.Bytes, prk.Bytes)
}
开发者ID:89hmdys,项目名称:toast,代码行数:30,代码来源:key.go


示例17: TestBlockHeaderPrecedenceGunFromPath

func TestBlockHeaderPrecedenceGunFromPath(t *testing.T) {
	// this is a proof of concept that if we have legacy fixtures with nested paths, we infer the gun from them correctly
	s := NewTestImportStore()

	from, _ := os.OpenFile("../fixtures/secure.example.com.key", os.O_RDONLY, notary.PrivExecPerms)
	defer from.Close()
	fromBytes, _ := ioutil.ReadAll(from)
	b, _ := pem.Decode(fromBytes)
	b.Headers["role"] = data.CanonicalSnapshotRole
	b.Headers["path"] = filepath.Join(notary.NonRootKeysSubdir, "anothergun", "12ba0e0a8e05e177bc2c3489bdb6d28836879469f078e68a4812fc8a2d521497")
	bBytes := pem.EncodeToMemory(b)

	in := bytes.NewBuffer(bBytes)

	err := ImportKeys(in, []Importer{s}, "somerole", "somegun", passphraseRetriever)
	require.NoError(t, err)

	require.Len(t, s.data, 1)
	for key := range s.data {
		// block header role= root should take precedence over command line flag
		require.Equal(t, "12ba0e0a8e05e177bc2c3489bdb6d28836879469f078e68a4812fc8a2d521497", key)
		final, rest := pem.Decode(s.data[key])
		require.Len(t, rest, 0)
		require.Equal(t, final.Headers["role"], "snapshot")
		require.Equal(t, final.Headers["gun"], "anothergun")
	}
}
开发者ID:jfrazelle,项目名称:notary,代码行数:27,代码来源:keys_test.go


示例18: TestBlockHeaderPrecedenceRoleAndGun

func TestBlockHeaderPrecedenceRoleAndGun(t *testing.T) {
	s := NewTestImportStore()

	from, _ := os.OpenFile("../fixtures/secure.example.com.key", os.O_RDONLY, notary.PrivExecPerms)
	defer from.Close()
	fromBytes, _ := ioutil.ReadAll(from)
	b, _ := pem.Decode(fromBytes)
	b.Headers["role"] = data.CanonicalSnapshotRole
	b.Headers["gun"] = "anothergun"
	bBytes := pem.EncodeToMemory(b)

	in := bytes.NewBuffer(bBytes)

	err := ImportKeys(in, []Importer{s}, "somerole", "somegun", passphraseRetriever)
	require.NoError(t, err)

	require.Len(t, s.data, 1)
	for key := range s.data {
		// block header role= root should take precedence over command line flag
		require.Equal(t, "12ba0e0a8e05e177bc2c3489bdb6d28836879469f078e68a4812fc8a2d521497", key)
		final, rest := pem.Decode(s.data[key])
		require.Len(t, rest, 0)
		require.Equal(t, final.Headers["role"], "snapshot")
		require.Equal(t, final.Headers["gun"], "anothergun")
	}
}
开发者ID:jfrazelle,项目名称:notary,代码行数:26,代码来源:keys_test.go


示例19: enc

func enc(text string) {
	fmt.Println(text)
	data := []byte(text)
	block, _ := pem.Decode([]byte(key["pri"]))
	privkey, _ := x509.ParsePKCS1PrivateKey(block.Bytes)
	encData, _ := PrivateEncrypt(privkey, data)
	fmt.Println(encData)

	fmt.Println(base64.StdEncoding.EncodeToString(encData))

	block2, _ := pem.Decode([]byte(key["pub"]))
	pubinterface, rest := x509.ParsePKIXPublicKey(block2.Bytes)
	if rest != nil {
		println("parse public key fail")
		return
	}
	plaindata, err := PublicDecrypt(pubinterface.(*rsa.PublicKey), encData)
	fmt.Println("N:" + base64.StdEncoding.EncodeToString(pubinterface.(*rsa.PublicKey).N.Bytes()))
	if err != nil {
		println(err)
		return
	}
	fmt.Println(string(plaindata))

}
开发者ID:jmptrader,项目名称:goexample,代码行数:25,代码来源:rsa_private_encrypt.go


示例20: TestSign

func TestSign(t *testing.T) {
	Convey("Given an XML, certificate, and RSA key", t, func() {
		pemString, _ := ioutil.ReadFile("./testdata/rsa.crt")
		pemBlock, _ := pem.Decode([]byte(pemString))
		cert, _ := x509.ParseCertificate(pemBlock.Bytes)

		pemString, _ = ioutil.ReadFile("./testdata/rsa.key")
		pemBlock, _ = pem.Decode([]byte(pemString))
		key, _ := x509.ParsePKCS1PrivateKey(pemBlock.Bytes)

		xml, _ := ioutil.ReadFile("./testdata/nosignature.xml")

		Convey("When generating the signature", func() {
			signer, _ := NewSigner(string(xml))
			xmlStr, err := signer.Sign(key)
			Convey("Then no error occurs", func() {
				So(err, ShouldBeNil)
			})
			Convey("And the signature should be valid", func() {
				validator, _ := NewValidator(xmlStr)
				validator.Certificates = append(validator.Certificates, *cert)
				err := validator.Validate()
				So(err, ShouldBeNil)
			})
		})
	})
}
开发者ID:ma314smith,项目名称:signedxml,代码行数:27,代码来源:signedxml_test.go



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang pem.Encode函数代码示例发布时间:2022-05-24
下一篇:
Golang json.Unmarshaler类代码示例发布时间:2022-05-24
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap