本文整理匯總了Golang中encoding/pem.Encode函數的典型用法代碼示例。如果您正苦於以下問題:Golang Encode函數的具體用法?Golang Encode怎麽用?Golang Encode使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了Encode函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: newCertificate
func newCertificate(dir string, prefix string) {
l.Infoln("Generating RSA key and certificate...")
priv, err := rsa.GenerateKey(rand.Reader, tlsRSABits)
l.FatalErr(err)
notBefore := time.Now()
notAfter := time.Date(2049, 12, 31, 23, 59, 59, 0, time.UTC)
template := x509.Certificate{
SerialNumber: new(big.Int).SetInt64(mr.Int63()),
Subject: pkix.Name{
CommonName: tlsName,
},
NotBefore: notBefore,
NotAfter: notAfter,
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth},
BasicConstraintsValid: true,
}
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
l.FatalErr(err)
certOut, err := os.Create(filepath.Join(dir, prefix+"cert.pem"))
l.FatalErr(err)
pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
certOut.Close()
keyOut, err := os.OpenFile(filepath.Join(dir, prefix+"key.pem"), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
l.FatalErr(err)
pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)})
keyOut.Close()
}
示例2: create
func (cmd *setcert) create(id string) error {
certFile, err := os.Create(id + ".crt")
if err != nil {
return err
}
defer certFile.Close()
keyFile, err := os.Create(id + ".key")
if err != nil {
return err
}
defer keyFile.Close()
priv, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return err
}
notBefore := time.Now()
notAfter := notBefore.Add(5 * 365 * 24 * time.Hour) // 5 years
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return err
}
template := x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{
Organization: []string{cmd.org},
},
NotBefore: notBefore,
NotAfter: notAfter,
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
BasicConstraintsValid: true,
}
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
if err != nil {
return err
}
err = pem.Encode(&cmd.encodedCert, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
if err != nil {
return err
}
_, err = certFile.Write(cmd.encodedCert.Bytes())
if err != nil {
return err
}
err = pem.Encode(keyFile, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)})
if err != nil {
return err
}
return nil
}
示例3: GenKeyPairIfNone
func GenKeyPairIfNone(privateName string, publicName string) {
dir, _ := filepath.Abs(filepath.Dir(os.Args[0]))
privatekey := filepath.Join(dir, privateName)
publickey := filepath.Join(dir, publicName)
if _, err := os.Stat(string(privatekey)); os.IsNotExist(err) {
log.Println("Generating JWT private key at ", string(privatekey))
k, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
log.Fatal(err)
}
var private pem.Block
private.Type = "RSA PRIVATE KEY"
private.Bytes = x509.MarshalPKCS1PrivateKey(k)
pp := new(bytes.Buffer)
pem.Encode(pp, &private)
err = ioutil.WriteFile(string(privatekey), pp.Bytes(), 0644)
if err != nil {
log.Fatal(err)
}
log.Println("Generating JWT public key at ", string(privatekey))
var public pem.Block
public.Type = "RSA PUBLIC KEY"
public.Bytes, _ = x509.MarshalPKIXPublicKey(&k.PublicKey)
ps := new(bytes.Buffer)
pem.Encode(ps, &public)
err = ioutil.WriteFile(string(publickey), ps.Bytes(), 0644)
if err != nil {
log.Fatal(err)
}
}
}
示例4: writeCertsAndKeys
func writeCertsAndKeys(template *x509.Certificate, certPath string, signeeKey *rsa.PrivateKey, keyPath string, parent *x509.Certificate, signingKey *rsa.PrivateKey) error {
derBytes, err := x509.CreateCertificate(rand.Reader, template, parent, &signeeKey.PublicKey, signingKey)
if err != nil {
return errors.Wrap(err, "Error creating certificate")
}
certBuffer := bytes.Buffer{}
if err := pem.Encode(&certBuffer, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}); err != nil {
return errors.Wrap(err, "Error encoding certificate")
}
keyBuffer := bytes.Buffer{}
if err := pem.Encode(&keyBuffer, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(signeeKey)}); err != nil {
return errors.Wrap(err, "Error encoding key")
}
if err := os.MkdirAll(filepath.Dir(certPath), os.FileMode(0755)); err != nil {
return errors.Wrap(err, "Error creating certificate directory")
}
if err := ioutil.WriteFile(certPath, certBuffer.Bytes(), os.FileMode(0644)); err != nil {
return errors.Wrap(err, "Error writing certificate to cert path")
}
if err := os.MkdirAll(filepath.Dir(keyPath), os.FileMode(0755)); err != nil {
return errors.Wrap(err, "Error creating key directory")
}
if err := ioutil.WriteFile(keyPath, keyBuffer.Bytes(), os.FileMode(0600)); err != nil {
return errors.Wrap(err, "Error writing key file")
}
return nil
}
示例5: main
func main() {
max := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, _ := rand.Int(rand.Reader, max)
subject := pkix.Name{
Organization: []string{"Manning Publications Co."},
OrganizationalUnit: []string{"Books"},
CommonName: "Go Web Programming",
}
template := x509.Certificate{
SerialNumber: serialNumber,
Subject: subject,
NotBefore: time.Now(),
NotAfter: time.Now().Add(365 * 24 * time.Hour),
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
IPAddresses: []net.IP{net.ParseIP("127.0.0.1")},
}
pk, _ := rsa.GenerateKey(rand.Reader, 2048)
derBytes, _ := x509.CreateCertificate(rand.Reader, &template, &template, &pk.PublicKey, pk)
certOut, _ := os.Create("cert.pem")
pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
certOut.Close()
keyOut, _ := os.Create("key.pem")
pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(pk)})
keyOut.Close()
}
示例6: genForNames
func (g *Generator) genForNames(names string) error {
certFileName := "cert.pem"
keyFileName := "key.pem"
rootCert, err := g.loadRootCA()
if err != nil {
return err
}
rootKey, err := g.loadRootCAKey()
if err != nil {
return err
}
priv, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return stackerr.Wrap(err)
}
now := time.Now()
template := x509.Certificate{
SerialNumber: new(big.Int).SetInt64(0),
Subject: pkix.Name{
CommonName: names,
},
NotBefore: now.Add(-5 * time.Minute).UTC(),
NotAfter: now.Add(g.MaxAge),
SubjectKeyId: []byte{1, 2, 3, 4},
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
BasicConstraintsValid: true,
}
derBytes, err := x509.CreateCertificate(
rand.Reader, &template, rootCert, &priv.PublicKey, rootKey)
if err != nil {
return stackerr.Wrap(err)
}
certOut, err := os.Create(certFileName)
if err != nil {
return stackerr.Wrap(err)
}
pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
certOut.Close()
log.Print("Written " + certFileName + "\n")
keyOut, err := os.OpenFile(keyFileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return stackerr.Wrap(err)
}
pem.Encode(keyOut, &pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(priv),
})
keyOut.Close()
log.Print("Written " + keyFileName + "\n")
return nil
return nil
}
示例7: GenerateSelfSignedCert
// Generate a 4096-bit RSA keypair and a Grumble auto-generated X509
// certificate. Output PEM-encoded DER representations of the resulting
// certificate and private key to certpath and keypath.
func GenerateSelfSignedCert(certpath, keypath string) (err error) {
now := time.Now()
tmpl := &x509.Certificate{
SerialNumber: big.NewInt(0),
Subject: pkix.Name{
CommonName: "Grumble Autogenerated Certificate",
},
NotBefore: now.Add(-300 * time.Second),
// Valid for 1 year.
NotAfter: now.Add(24 * time.Hour * 365),
SubjectKeyId: []byte{1, 2, 3, 4},
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
}
priv, err := rsa.GenerateKey(rand.Reader, 4096)
if err != nil {
return err
}
certbuf, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &priv.PublicKey, priv)
if err != nil {
log.Printf("Error: %v", err)
return err
}
certblk := pem.Block{
Type: "CERTIFICATE",
Bytes: certbuf,
}
keybuf := x509.MarshalPKCS1PrivateKey(priv)
keyblk := pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: keybuf,
}
certfn := filepath.Join(Args.DataDir, "cert.pem")
file, err := os.OpenFile(certfn, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0700)
if err != nil {
return err
}
defer file.Close()
err = pem.Encode(file, &certblk)
if err != nil {
return err
}
keyfn := filepath.Join(Args.DataDir, "key.pem")
file, err = os.OpenFile(keyfn, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0700)
if err != nil {
return err
}
defer file.Close()
err = pem.Encode(file, &keyblk)
if err != nil {
return err
}
return nil
}
示例8: GenerateCerts
func (c *Cert) GenerateCerts(domain string) ([]byte, []byte, []byte, []byte, error) {
caPrivateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, nil, nil, nil, err
}
encodedCAPrivateKey := new(bytes.Buffer)
if err := pem.Encode(encodedCAPrivateKey, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(caPrivateKey)}); err != nil {
return nil, nil, nil, nil, err
}
caTemplate := c.generateTemplate(domain, true)
encodedCACertificate, err := c.generateCert(caTemplate, caTemplate, &caPrivateKey.PublicKey, caPrivateKey)
if err != nil {
return nil, nil, nil, nil, err
}
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, nil, nil, nil, err
}
encodedPrivateKey := new(bytes.Buffer)
if err := pem.Encode(encodedPrivateKey, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)}); err != nil {
return nil, nil, nil, nil, err
}
template := c.generateTemplate(domain, false)
encodedCertificate, err := c.generateCert(template, caTemplate, &privateKey.PublicKey, caPrivateKey)
if err != nil {
return nil, nil, nil, nil, err
}
return encodedCertificate, encodedPrivateKey.Bytes(), encodedCACertificate, encodedCAPrivateKey.Bytes(), nil
}
示例9: ExportKeys
// exports the keys of a chatroom.
func (room *chatroom) ExportKeys() {
// public key of the room
publicFilename := fmt.Sprintf("chatrooms/%s_public.pem", room.ID)
publicPemFile, err := os.Create(publicFilename)
if err != nil {
log.Fatalf("Failed to open %s_public.pem for writing: %s", room.ID, err)
return
}
pem.Encode(publicPemFile, &pem.Block{Type: "GROUP PUBLIC KEY", Bytes: room.groupPrivateKey.Group.Marshal()})
publicPemFile.Close()
// private key of the room - this is the key that allows creation of new members
privateFilename := fmt.Sprintf("chatrooms/%s_private.pem", room.ID)
privatePemFile, err := os.Create(privateFilename)
if err != nil {
log.Fatalf("Failed to open %s_private.pem for writing: %s", room.ID, err)
return
}
pem.Encode(privatePemFile, &pem.Block{Type: "GROUP PRIVATE KEY", Bytes: room.groupPrivateKey.Marshal()})
privatePemFile.Close()
// a member's private key
memberFileName := fmt.Sprintf("keys/%s_member.pem", room.ID)
memberPemFile, err := os.Create(memberFileName)
if err != nil {
log.Fatalf("Failed to open %s_member.pem for writing: %s", room.ID, err)
return
}
pem.Encode(memberPemFile, &pem.Block{Type: "MEMBER PRIVATE KEY", Bytes: room.memberPrivateKey.Marshal()})
memberPemFile.Close()
}
示例10: GenerateAndSave
// GenerateAndSave - generates cert and key and saves them on your disk
func GenerateAndSave(name, organization string, validity time.Duration) (tlsc *tls.Certificate, err error) {
x509c, priv, err := NewCertificatePair(name, organization, validity)
if err != nil {
log.Fatalf("Failed to generate certificate and key pair, got error: %s", err.Error())
}
certOut, err := os.Create("cert.pem")
if err != nil {
log.Errorf("failed to open cert.pem for writing: %s", err.Error())
return
}
pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: x509c.Raw})
certOut.Close()
log.Print("cert.pem created\n")
keyOut, err := os.OpenFile("key.pem", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
log.Errorf("failed to open key.pem for writing: %s", err.Error())
return
}
pem.Encode(keyOut, PemBlockForKey(priv))
keyOut.Close()
log.Print("key.pem created.\n")
tlsc, err = GetTLSCertificate(x509c, priv, "hoverfly.proxy", validity)
if err != nil {
log.Errorf("failed to get tls certificate: %s", err.Error())
}
return
}
示例11: GenerateInvite
// Generates pem files and stores them in invites/.
func (room *chatroom) GenerateInvite() {
newMember, err := room.groupPrivateKey.NewMember(rand.Reader)
if err != nil {
// shit
}
publicFilename := fmt.Sprintf("invites/%s_public.pem", room.ID)
publicPemFile, err := os.Create(publicFilename)
if err != nil {
log.Fatalf("Failed to open %s_public.pem for writing: %s", room.ID, err)
return
}
pem.Encode(publicPemFile, &pem.Block{Type: "GROUP PUBLIC KEY", Bytes: room.groupPrivateKey.Group.Marshal()})
publicPemFile.Close()
memberFileName := fmt.Sprintf("invites/%s_member.pem", room.ID)
memberPemFile, err := os.Create(memberFileName)
if err != nil {
log.Fatalf("Failed to open %s_member.pem for writing: %s", room.ID, err)
return
}
pem.Encode(memberPemFile, &pem.Block{Type: "MEMBER PRIVATE KEY", Bytes: newMember.Marshal()})
memberPemFile.Close()
}
示例12: createCertificate
// createCertificate creates a certificate from the supplied template:
// template: an x509 template describing the certificate to generate.
// parent: either a CA certificate, or template (for self-signed). If nil, will use template.
// templateKey: the private key for the certificate supplied as template
// parentKey: the private key for the certificate supplied as parent (whether CA or self-signed). If nil will use templateKey
//
// return PEM encoded certificate and key
func createCertificate(template, parent *x509.Certificate, templateKey, parentKey *rsa.PrivateKey) (cert bytes.Buffer, key bytes.Buffer, err error) {
defer trace.End(trace.Begin(""))
if parent == nil {
parent = template
}
if parentKey == nil {
parentKey = templateKey
}
derBytes, err := x509.CreateCertificate(rand.Reader, template, parent, &templateKey.PublicKey, parentKey)
if err != nil {
err = errors.Errorf("Failed to generate x509 certificate: %s", err)
return cert, key, err
}
err = pem.Encode(&cert, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
if err != nil {
err = errors.Errorf("Failed to encode x509 certificate: %s", err)
return cert, key, err
}
err = pem.Encode(&key, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(templateKey)})
if err != nil {
err = errors.Errorf("Failed to encode tls key pairs: %s", err)
return cert, key, err
}
return cert, key, nil
}
示例13: createSigningCertificate
func createSigningCertificate(signerId string) error {
// generate private key
fmt.Println("Generating signing keys. This may take a minute...")
signerKey, err := rsa.GenerateKey(rand.Reader, 4096)
if err != nil {
return err
}
signerCert, err := su3.NewSigningCertificate(signerId, signerKey)
if nil != err {
return err
}
// save cert
certFile := signerFile(signerId) + ".crt"
certOut, err := os.Create(certFile)
if err != nil {
return fmt.Errorf("failed to open %s for writing: %s\n", certFile, err)
}
pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: signerCert})
certOut.Close()
fmt.Println("signing certificate saved to:", certFile)
// save signing private key
privFile := signerFile(signerId) + ".pem"
keyOut, err := os.OpenFile(privFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return fmt.Errorf("failed to open %s for writing: %s\n", privFile, err)
}
pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(signerKey)})
keyOut.Close()
fmt.Println("signing private key saved to:", privFile)
return nil
}
示例14: createTLSCertificate
func createTLSCertificate(host string) error {
fmt.Println("Generating TLS keys. This may take a minute...")
priv, err := rsa.GenerateKey(rand.Reader, 4096)
if err != nil {
return err
}
tlsCert, err := reseed.NewTLSCertificate(host, priv)
if nil != err {
return err
}
// save the TLS certificate
certOut, err := os.Create(host + ".crt")
if err != nil {
return fmt.Errorf("failed to open %s for writing: %s", host+".crt", err)
}
pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: tlsCert})
certOut.Close()
fmt.Printf("TLS certificate saved to: %s\n", host+".crt")
// save the TLS private key
privFile := host + ".pem"
keyOut, err := os.OpenFile(privFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return fmt.Errorf("failed to open %s for writing: %s\n", privFile, err)
}
pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)})
keyOut.Close()
fmt.Printf("TLS private key saved to: %s\n", privFile)
return nil
}
示例15: makeCert
// makeCert creates a self-signed RSA certificate.
// taken from crypto/tls/generate_cert.go
func makeCert(host string, validFor time.Duration) (certPEM, keyPEM []byte) {
const bits = 1024
priv, err := rsa.GenerateKey(rand.Reader, bits)
if err != nil {
log.Fatalf("Failed to generate private key: %s", err)
}
template := x509.Certificate{
SerialNumber: big.NewInt(1),
Subject: pkix.Name{
Organization: []string{"Fabio Co"},
},
NotBefore: time.Now(),
NotAfter: time.Now().Add(validFor),
IsCA: true,
DNSNames: []string{host},
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
}
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
if err != nil {
log.Fatalf("Failed to create certificate: %s", err)
}
var cert, key bytes.Buffer
pem.Encode(&cert, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
pem.Encode(&key, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)})
return cert.Bytes(), key.Bytes()
}