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

Golang pem.EncodeToMemory函数代码示例

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

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



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

示例1: GenerateCertificateForTest

func GenerateCertificateForTest() *v2tls.Certificate {
	priv, err := rsa.GenerateKey(rand.Reader, 2048)
	common.Must(err)

	serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
	serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
	if err != nil {
		log.Fatalf("failed to generate serial number: %s", err)
	}

	template := x509.Certificate{
		SerialNumber: serialNumber,
		Subject: pkix.Name{
			Organization: []string{"V2Ray Inc"},
		},
		NotBefore:             time.Now(),
		NotAfter:              time.Now().Add(time.Hour),
		KeyUsage:              x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
		ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
		BasicConstraintsValid: true,
		DNSNames:              []string{"www.v2ray.com"},
	}

	derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
	common.Must(err)

	certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
	keyPEM := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)})

	return &v2tls.Certificate{
		Certificate: certPEM,
		Key:         keyPEM,
	}
}
开发者ID:ylywyn,项目名称:v2ray-core,代码行数:34,代码来源:tls.go


示例2: GenerateServer

func (crtkit *CertKit) GenerateServer(subject pkix.Name, host, email string, NotBefore ...time.Time) error {
	var e error
	var derBytes []byte
	var notBefore time.Time

	priv, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		return errors.New(fmt.Sprintf("failed to generate private key: %s", err))
	}

	if len(NotBefore) > 0 {
		notBefore = NotBefore[0]
	} else {
		notBefore = time.Now()
	}
	serialNumber, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
	if err != nil {
		return errors.New(fmt.Sprintf("failed to generate serial number: %s", err))
	}

	if host == "" {
		host, _ = os.Hostname()
	}

	Goose.Generator.Logf(6, "Certificate authority used: %#v", crtkit.CACert)

	template := x509.Certificate{
		SerialNumber:          serialNumber,
		Subject:               subject,
		IsCA:                  false,
		NotBefore:             notBefore,
		NotAfter:              notBefore.Add(365 * 24 * time.Hour),
		DNSNames:              []string{host, strings.Split(host, ".")[0]},
		AuthorityKeyId:        crtkit.CACert.SubjectKeyId,
		KeyUsage:              x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageContentCommitment,
		ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth},
		BasicConstraintsValid: true,
	}

	Goose.Generator.Logf(4, "X509 Template: %#v", template)

	if crtkit.CACert.CRLDistributionPoints != nil {
		template.CRLDistributionPoints = crtkit.CACert.CRLDistributionPoints
	} else {
		Goose.Generator.Logf(1, "Certificate authority without CRL distribution points")
	}

	crtkit.ServerKey = priv
	crtkit.ServerCert = &template
	derBytes, e = x509.CreateCertificate(rand.Reader, &template, crtkit.CACert, &priv.PublicKey, crtkit.CAKey)
	if e != nil {
		return errors.New(fmt.Sprintf("Failed to create certificate: %s", e))
	}
	Goose.Generator.Logf(4, "DER Certificate: %s", derBytes)
	crtkit.ServerCertPem = pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
	crtkit.ServerKeyPem = pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)})
	Goose.Generator.Logf(4, "PEM Certificate: %s", crtkit.ServerCertPem)

	return nil
}
开发者ID:luisfurquim,项目名称:stonelizard,代码行数:60,代码来源:gencert.go


示例3: GenerateKey

func GenerateKey() (pkPem []byte, pubkPem []byte, pubSSHAK []byte, err error) {
	pk, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		return
	}
	pkDer := x509.MarshalPKCS1PrivateKey(pk)
	pkBlock := pem.Block{
		Type:    "RSA PRIVATE KEY",
		Headers: nil,
		Bytes:   pkDer,
	}
	pkPem = pem.EncodeToMemory(&pkBlock)

	pubk := pk.PublicKey
	pubkDer, err := x509.MarshalPKIXPublicKey(&pubk)
	if err != nil {
		return
	}

	pubkBlock := pem.Block{
		Type:    "PUBLIC KEY",
		Headers: nil,
		Bytes:   pubkDer,
	}
	pubkPem = pem.EncodeToMemory(&pubkBlock)

	pubSSH, err := ssh.NewPublicKey(&pubk)
	if err != nil {
		return
	}
	pubSSHAK = ssh.MarshalAuthorizedKey(pubSSH)

	return
}
开发者ID:41px,项目名称:dmz,代码行数:34,代码来源:rsa.go


示例4: Export

func (reg Registration) Export(password string) (*RegistrationExport, error) {
	keyBlock, err := reg.SigningKey.EncryptPrivateKey(password, utils.PemDefaultCipher)
	if nil != err {
		return nil, err
	}
	jsonBytes, err := json.Marshal(rawRegistrationExportJson{
		Resource:           reg.Resource,
		LinkTermsOfService: reg.LinkTermsOfService,
		RecoveryToken:      reg.RecoveryToken,
	})
	if nil != err {
		return nil, err
	}
	jsonBlock := &pem.Block{
		Type:  pemTypeAcmeJsonRegistration,
		Bytes: jsonBytes,
	}
	if err := utils.EncryptPemBlock(jsonBlock, password, utils.PemDefaultCipher); nil != err {
		return nil, err
	}
	return &RegistrationExport{
		JsonPem:       pem.EncodeToMemory(jsonBlock),
		SigningKeyPem: pem.EncodeToMemory(keyBlock),
		Location:      reg.Location,
		Name:          reg.Name,
	}, nil
}
开发者ID:NeuralSpaz,项目名称:go-acme-client,代码行数:27,代码来源:export_registration.go


示例5: generateSshKeyUsingGo

func generateSshKeyUsingGo() (string, string, error) {
	privateKey, err := rsa.GenerateKey(rand.Reader, 2014)
	if err != nil {
		return "", "", err
	}

	fmt.Printf("----> creating ssh private key using Golang\n")
	privateKeyDer := x509.MarshalPKCS1PrivateKey(privateKey)
	privateKeyBlock := pem.Block{
		Type:    "RSA PRIVATE KEY",
		Headers: nil,
		Bytes:   privateKeyDer,
	}
	privateKeyPem := string(pem.EncodeToMemory(&privateKeyBlock))

	fmt.Printf("----> creating ssh public key using Golang\n")
	publicKey := privateKey.PublicKey
	publicKeyDer, err := x509.MarshalPKIXPublicKey(&publicKey)
	if err != nil {
		return "", "", err
	}

	publicKeyBlock := pem.Block{
		Type:    "PUBLIC KEY",
		Headers: nil,
		Bytes:   publicKeyDer,
	}

	publicKeyPem := string(pem.EncodeToMemory(&publicKeyBlock))

	return privateKeyPem, publicKeyPem, nil
}
开发者ID:digideskweb,项目名称:bosh-softlayer-cpi,代码行数:32,代码来源:test_helpers.go


示例6: CreatePrivateKey

func CreatePrivateKey(d *schema.ResourceData, meta interface{}) error {
	keyAlgoName := d.Get("algorithm").(string)
	var keyFunc keyAlgo
	var ok bool
	if keyFunc, ok = keyAlgos[keyAlgoName]; !ok {
		return fmt.Errorf("invalid key_algorithm %#v", keyAlgoName)
	}

	key, err := keyFunc(d)
	if err != nil {
		return err
	}

	var keyPemBlock *pem.Block
	switch k := key.(type) {
	case *rsa.PrivateKey:
		keyPemBlock = &pem.Block{
			Type:  "RSA PRIVATE KEY",
			Bytes: x509.MarshalPKCS1PrivateKey(k),
		}
	case *ecdsa.PrivateKey:
		keyBytes, err := x509.MarshalECPrivateKey(k)
		if err != nil {
			return fmt.Errorf("error encoding key to PEM: %s", err)
		}
		keyPemBlock = &pem.Block{
			Type:  "EC PRIVATE KEY",
			Bytes: keyBytes,
		}
	default:
		return fmt.Errorf("unsupported private key type")
	}
	keyPem := string(pem.EncodeToMemory(keyPemBlock))

	pubKey := publicKey(key)
	pubKeyBytes, err := x509.MarshalPKIXPublicKey(pubKey)
	if err != nil {
		return fmt.Errorf("failed to marshal public key: %s", err)
	}
	pubKeyPemBlock := &pem.Block{
		Type:  "PUBLIC KEY",
		Bytes: pubKeyBytes,
	}

	d.SetId(hashForState(string((pubKeyBytes))))
	d.Set("private_key_pem", keyPem)
	d.Set("public_key_pem", string(pem.EncodeToMemory(pubKeyPemBlock)))

	sshPubKey, err := ssh.NewPublicKey(pubKey)
	if err == nil {
		// Not all EC types can be SSH keys, so we'll produce this only
		// if an appropriate type was selected.
		sshPubKeyBytes := ssh.MarshalAuthorizedKey(sshPubKey)
		d.Set("public_key_openssh", string(sshPubKeyBytes))
	} else {
		d.Set("public_key_openssh", "")
	}

	return nil
}
开发者ID:RezaDKhan,项目名称:terraform,代码行数:60,代码来源:resource_private_key.go


示例7: newLeaf

// newLeaf generates a certificate/key pair suitable for use by a leaf node.
func newLeaf(caCertPEM, caKeyPEM string, expiry time.Time, hostnames []string, extKeyUsage []x509.ExtKeyUsage) (certPEM, keyPEM string, err error) {
	tlsCert, err := tls.X509KeyPair([]byte(caCertPEM), []byte(caKeyPEM))
	if err != nil {
		return "", "", err
	}
	if len(tlsCert.Certificate) != 1 {
		return "", "", fmt.Errorf("more than one certificate for CA")
	}
	caCert, err := x509.ParseCertificate(tlsCert.Certificate[0])
	if err != nil {
		return "", "", err
	}
	if !caCert.BasicConstraintsValid || !caCert.IsCA {
		return "", "", fmt.Errorf("CA certificate is not a valid CA")
	}
	caKey, ok := tlsCert.PrivateKey.(*rsa.PrivateKey)
	if !ok {
		return "", "", fmt.Errorf("CA private key has unexpected type %T", tlsCert.PrivateKey)
	}
	key, err := rsa.GenerateKey(rand.Reader, KeyBits)
	if err != nil {
		return "", "", fmt.Errorf("cannot generate key: %v", err)
	}
	now := time.Now()
	template := &x509.Certificate{
		SerialNumber: new(big.Int),
		Subject: pkix.Name{
			// This won't match host names with dots. The hostname
			// is hardcoded when connecting to avoid the issue.
			CommonName:   "*",
			Organization: []string{"juju"},
		},
		NotBefore: now.UTC().AddDate(0, 0, -7),
		NotAfter:  expiry.UTC(),

		SubjectKeyId: bigIntHash(key.N),
		KeyUsage:     x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageKeyAgreement,
		ExtKeyUsage:  extKeyUsage,
	}
	for _, hostname := range hostnames {
		if ip := net.ParseIP(hostname); ip != nil {
			template.IPAddresses = append(template.IPAddresses, ip)
		} else {
			template.DNSNames = append(template.DNSNames, hostname)
		}
	}
	certDER, err := x509.CreateCertificate(rand.Reader, template, caCert, &key.PublicKey, caKey)
	if err != nil {
		return "", "", err
	}
	certPEMData := pem.EncodeToMemory(&pem.Block{
		Type:  "CERTIFICATE",
		Bytes: certDER,
	})
	keyPEMData := pem.EncodeToMemory(&pem.Block{
		Type:  "RSA PRIVATE KEY",
		Bytes: x509.MarshalPKCS1PrivateKey(key),
	})
	return string(certPEMData), string(keyPEMData), nil
}
开发者ID:imoapps,项目名称:juju,代码行数:61,代码来源:cert.go


示例8: newConfig

func newConfig() (client, server *tls.Config) {
	now := time.Now()
	tpl := x509.Certificate{
		SerialNumber:          new(big.Int).SetInt64(42),
		Subject:               pkix.Name{CommonName: ServerName},
		NotBefore:             now.Add(-2 * time.Hour).UTC(),
		NotAfter:              now.Add(2 * time.Hour).UTC(),
		BasicConstraintsValid: true,
		IsCA: true,
	}
	priv, err := rsa.GenerateKey(rand.Reader, 512)
	if err != nil {
		panic(err)
	}
	crt, err := x509.CreateCertificate(rand.Reader, &tpl, &tpl, &priv.PublicKey, priv)
	if err != nil {
		panic(err)
	}
	key := x509.MarshalPKCS1PrivateKey(priv)
	pair, err := tls.X509KeyPair(
		pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: crt}),
		pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: key}),
	)
	if err != nil {
		panic(err)
	}
	root, err := x509.ParseCertificate(crt)
	if err != nil {
		panic(err)
	}
	server = &tls.Config{Certificates: []tls.Certificate{pair}}
	client = &tls.Config{RootCAs: x509.NewCertPool(), ServerName: ServerName}
	client.RootCAs.AddCert(root)
	return
}
开发者ID:jappre,项目名称:mutation,代码行数:35,代码来源:tls.go


示例9: TestExportKeysByID

func TestExportKeysByID(t *testing.T) {
	s := NewTestExportStore()

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

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

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

	s.data["ankh"] = bBytes
	s.data["morpork/identifier"] = cBytes

	buf := bytes.NewBuffer(nil)

	err := ExportKeysByID(buf, s, []string{"identifier"})
	require.NoError(t, err)

	out, err := ioutil.ReadAll(buf)
	require.NoError(t, err)

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


示例10: newKey

// newKey realiza la generación y codificación de las claves RSA en codificación PEM.
func newKey() *Key {
	privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		log.LogE("failed to generate private key", "pkg", "try6", "func", "NewKey(string) *Key", "error", err.Error())
		return nil
	}
	privPEM := pem.EncodeToMemory(
		&pem.Block{
			Type:  "RSA PRIVATE KEY",
			Bytes: x509.MarshalPKCS1PrivateKey(privateKey),
		},
	)
	pubKeyPKIX, err := x509.MarshalPKIXPublicKey(&privateKey.PublicKey)
	if err != nil {
		log.LogE("failed to generate DER public key", "pkg", "try6", "func", "NewKey(string) *Key", "error", err.Error())
		return nil
	}

	pubPEM := pem.EncodeToMemory(&pem.Block{
		Type:  "RSA PUBLIC KEY",
		Bytes: pubKeyPKIX,
	})

	return &Key{
		PubKey:  pubPEM,
		PrivKey: privPEM,
	}
}
开发者ID:jllopis,项目名称:try6,代码行数:29,代码来源:keys.go


示例11: jwsTestKey

func jwsTestKey(notBefore, notAfter time.Time) (pemKey []byte, pemCert []byte) {
	key, err := rsa.GenerateKey(rand.Reader, 1024)
	if err != nil {
		panic(fmt.Sprintf("rsa.GenerateKey: %v", err))
	}
	pemKey = pem.EncodeToMemory(&pem.Block{
		Type:  "RSA PRIVATE KEY",
		Bytes: x509.MarshalPKCS1PrivateKey(key),
	})

	tcert := x509.Certificate{
		SerialNumber:          big.NewInt(1),
		Subject:               pkix.Name{CommonName: "www.example.org"},
		Issuer:                pkix.Name{CommonName: "www.example.org"},
		NotBefore:             notBefore,
		NotAfter:              notAfter,
		KeyUsage:              x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
		ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
		BasicConstraintsValid: true,
	}

	var cert []byte
	cert, err = x509.CreateCertificate(rand.Reader, &tcert, &tcert, &key.PublicKey, key)
	if err != nil {
		panic(fmt.Sprintf("x509.CreateCertificate: %v", err))
	}
	pemCert = pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert})

	return pemKey, pemCert
}
开发者ID:pathikdevani,项目名称:ioweb2015,代码行数:30,代码来源:main_test.go


示例12: genKey

func genKey() (private, public []byte) {
	priKey, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		fmt.Println(err)
		return
	}
	priDer := x509.MarshalPKCS1PrivateKey(priKey)
	private = pem.EncodeToMemory(
		&pem.Block{
			Type:  "RSA PRIVATE KEY",
			Bytes: priDer,
		},
	)

	pub := priKey.PublicKey
	pubDer, err := x509.MarshalPKIXPublicKey(&pub)
	if err != nil {
		fmt.Println(err)
		return
	}
	public = pem.EncodeToMemory(
		&pem.Block{
			Type:    "PUBLIC KEY",
			Headers: nil,
			Bytes:   pubDer,
		},
	)
	ioutil.WriteFile("public.pem", public, 0644)
	ioutil.WriteFile("private.pem", private, 0644)
	return
}
开发者ID:0x9e3779b9,项目名称:golang_lab,代码行数:31,代码来源:main.go


示例13: generateRSAKeys

func generateRSAKeys(bits int) (string, string, error) {
	if err := validateRSABits(bits); err != nil {
		return "", "", err
	}
	privateKey, err := rsa.GenerateKey(rand.Reader, bits)
	if err != nil {
		return "", "", err
	}
	pubASN1, err := x509.MarshalPKIXPublicKey(&privateKey.PublicKey)
	if err != nil {
		return "", "", err
	}
	publicKeyBytes := pem.EncodeToMemory(
		&pem.Block{
			Type:  rsaPublicBlockType,
			Bytes: pubASN1,
		},
	)
	privateKeyBytes := pem.EncodeToMemory(
		&pem.Block{
			Type:  rsaPrivateBlockType,
			Bytes: x509.MarshalPKCS1PrivateKey(privateKey),
		},
	)
	return string(publicKeyBytes), string(privateKeyBytes), nil
}
开发者ID:codeship,项目名称:go-encrypt,代码行数:26,代码来源:rsa.go


示例14: TestTLSConnection

func TestTLSConnection(t *testing.T) {
	reactor := NewReactor()
	client := reactor.CreateServer("local")

	initialiseServerConnection(client)

	// generate a test certificate to use
	priv, _ := ecdsa.GenerateKey(elliptic.P521(), rand.Reader)

	duration30Days, _ := time.ParseDuration("-30h")
	notBefore := time.Now().Add(duration30Days) // valid 30 hours ago
	duration1Year, _ := time.ParseDuration("90h")
	notAfter := notBefore.Add(duration1Year) // for 90 hours

	serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
	serialNumber, _ := rand.Int(rand.Reader, serialNumberLimit)

	template := x509.Certificate{
		SerialNumber: serialNumber,
		Subject: pkix.Name{
			Organization: []string{"gIRC-Go Co"},
		},
		NotBefore:             notBefore,
		NotAfter:              notAfter,
		KeyUsage:              x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
		ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
		BasicConstraintsValid: true,
		IsCA: true,
	}

	template.IPAddresses = append(template.IPAddresses, net.ParseIP("127.0.0.1"))
	template.IPAddresses = append(template.IPAddresses, net.ParseIP("::"))
	template.DNSNames = append(template.DNSNames, "localhost")

	derBytes, _ := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)

	c := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
	b, _ := x509.MarshalECPrivateKey(priv)
	k := pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: b})

	// we mock up a server connection to test the client
	listenerKeyPair, _ := tls.X509KeyPair(c, k)

	var listenerTLSConfig tls.Config
	listenerTLSConfig.Certificates = make([]tls.Certificate, 0)
	listenerTLSConfig.Certificates = append(listenerTLSConfig.Certificates, listenerKeyPair)
	listener, _ := tls.Listen("tcp", ":0", &listenerTLSConfig)

	// mock up the client side too
	clientTLSCertPool := x509.NewCertPool()
	clientTLSCertPool.AppendCertsFromPEM(c)

	var clientTLSConfig tls.Config
	clientTLSConfig.RootCAs = clientTLSCertPool
	clientTLSConfig.ServerName = "localhost"
	go client.Connect(listener.Addr().String(), true, &clientTLSConfig)
	go client.ReceiveLoop()

	testServerConnection(t, reactor, client, listener)
}
开发者ID:DanielOaks,项目名称:girc-go,代码行数:60,代码来源:reactor_test.go


示例15: getCertificate

func getCertificate(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) {
	fmt.Printf("getCertificate(%#v)", clientHello)
	// name := clientHello.ServerName
	name := "www.gov.cn"
	glog.Infof("Generating RootCA for %s", name)
	template := x509.Certificate{
		IsCA:         true,
		SerialNumber: big.NewInt(1),
		Subject: pkix.Name{
			Organization: []string{name},
		},
		NotBefore: time.Now().Add(-time.Duration(5 * time.Minute)),
		NotAfter:  time.Now().Add(180 * 24 * time.Hour),

		KeyUsage:              x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
		ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
		BasicConstraintsValid: true,
	}

	priv, err := rsa.GenerateKey(rand.Reader, 1024)
	if err != nil {
		return nil, err
	}

	derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
	if err != nil {
		return nil, err
	}

	certPEMBlock := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
	keyPEMBlock := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)})

	cert, err := tls.X509KeyPair(certPEMBlock, keyPEMBlock)
	return &cert, err
}
开发者ID:snowink,项目名称:goproxy,代码行数:35,代码来源:vps.go


示例16: CreateTLS

func CreateTLS() *tls.Config {
	priv, err := rsa.GenerateKey(rand.Reader, 2048)

	if err != nil {
		log.Fatal("failed to generate private key:", err)
	}

	var notBefore time.Time
	notBefore = time.Now()
	notAfter := notBefore.Add(365 * 24 * time.Hour)

	serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
	serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
	if err != nil {
		log.Fatal("failed to generate serial number:", err)
	}

	template := x509.Certificate{
		SerialNumber: serialNumber,
		Subject: pkix.Name{
			Organization: []string{"Wago"},
		},
		NotBefore: notBefore,
		NotAfter:  notAfter,

		KeyUsage:              x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
		ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
		BasicConstraintsValid: true,
	}

	hosts := []string{"127.0.0.1", "::1", "localhost"}
	for _, h := range hosts {
		if ip := net.ParseIP(h); ip != nil {
			template.IPAddresses = append(template.IPAddresses, ip)
		} else {
			template.DNSNames = append(template.DNSNames, h)
		}
	}

	template.IsCA = true
	template.KeyUsage |= x509.KeyUsageCertSign

	derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
	if err != nil {
		log.Fatal("Failed to create certificate:", err)
	}

	certPEMBlock := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derBytes})

	keyPEMBlock := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)})

	cert, err := tls.X509KeyPair(certPEMBlock, keyPEMBlock)
	if err != nil {
		log.Fatal(err)
	}

	return &tls.Config{
		Certificates: []tls.Certificate{cert},
	}
}
开发者ID:JonahBraun,项目名称:sweetdrop,代码行数:60,代码来源:tls.go


示例17: createTLSConfig

func createTLSConfig(host string) (certPEMBlock, keyPEMBlock []byte, err error) {
	now := time.Now()
	tpl := x509.Certificate{
		SerialNumber:          new(big.Int).SetInt64(0),
		Subject:               pkix.Name{CommonName: host},
		NotBefore:             now.Add(-24 * time.Hour).UTC(),
		NotAfter:              now.AddDate(1, 0, 0).UTC(),
		KeyUsage:              x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
		BasicConstraintsValid: true,
		MaxPathLen:            1,
		IsCA:                  true,
		SubjectKeyId:          []byte{1, 2, 3, 4},
		Version:               2,
	}
	key, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		return
	}
	der, err := x509.CreateCertificate(rand.Reader, &tpl, &tpl, &key.PublicKey, key)
	if err != nil {
		return
	}
	certPEMBlock = pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})
	keyPEMBlock = pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)})
	return
}
开发者ID:projectarkc,项目名称:psiphon,代码行数:26,代码来源:meek-server.go


示例18: GenerateKeyPair

// generate RSA key pair
func GenerateKeyPair() (map[string]string, error) {

	kp := make(map[string]string)
	privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		return kp, err
	}

	// calculations to speed up private key operations and
	// some basic sanity checks
	privateKey.Precompute()
	if err = privateKey.Validate(); err != nil {
		return kp, err
	}

	// convert private key to pem encode
	privBlock := &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)}
	privPEMData := pem.EncodeToMemory(privBlock)

	// convert public key to pem encode
	PubASN1, err := x509.MarshalPKIXPublicKey(&privateKey.PublicKey)
	if err != nil {
		return kp, err
	}

	pubPEMData := pem.EncodeToMemory(&pem.Block{
		Type:  "PUBLIC KEY",
		Bytes: PubASN1,
	})

	kp["private_key"] = string(privPEMData)
	kp["public_key"] = string(pubPEMData)

	return kp, nil
}
开发者ID:stonedoc,项目名称:stone,代码行数:36,代码来源:crypto.go


示例19: createCAKeyPair

func (ca *CA) createCAKeyPair(name string) *ecdsa.PrivateKey {
	caLogger.Debug("Creating CA key pair.")

	curve := primitives.GetDefaultCurve()

	priv, err := ecdsa.GenerateKey(curve, rand.Reader)
	if err == nil {
		raw, _ := x509.MarshalECPrivateKey(priv)
		cooked := pem.EncodeToMemory(
			&pem.Block{
				Type:  "ECDSA PRIVATE KEY",
				Bytes: raw,
			})
		err = ioutil.WriteFile(ca.path+"/"+name+".priv", cooked, 0644)
		if err != nil {
			caLogger.Panic(err)
		}

		raw, _ = x509.MarshalPKIXPublicKey(&priv.PublicKey)
		cooked = pem.EncodeToMemory(
			&pem.Block{
				Type:  "ECDSA PUBLIC KEY",
				Bytes: raw,
			})
		err = ioutil.WriteFile(ca.path+"/"+name+".pub", cooked, 0644)
		if err != nil {
			caLogger.Panic(err)
		}
	}
	if err != nil {
		caLogger.Panic(err)
	}

	return priv
}
开发者ID:yoshiharay,项目名称:fabric,代码行数:35,代码来源:ca.go


示例20: genKeyPair

func genKeyPair(keySize int) (string, string, error) {
	prikey, err := rsa.GenerateKey(rand.Reader, keySize)
	if err != nil {
		return "", "", err
	}

	marshaled := x509.MarshalPKCS1PrivateKey(prikey)
	marshaledPublic, errpk := x509.MarshalPKIXPublicKey(&prikey.PublicKey)
	if errpk != nil {
		return "", "", errpk
	}

	privateKeyPEM := pem.EncodeToMemory(&pem.Block{
		Type:    "RSA PRIVATE KEY",
		Headers: nil,
		Bytes:   marshaled,
	})

	publicKeyPEM := pem.EncodeToMemory(&pem.Block{
		Type:    "RSA PUBLIC KEY",
		Headers: nil,
		Bytes:   marshaledPublic,
	})

	return string(privateKeyPEM), string(publicKeyPEM), nil
}
开发者ID:Pronovix,项目名称:gopush,代码行数:26,代码来源:crypto.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Golang pem.Block类代码示例发布时间:2022-05-24
下一篇:
Golang pem.Encode函数代码示例发布时间: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