本文整理汇总了Golang中encoding/pem.Encode函数的典型用法代码示例。如果您正苦于以下问题:Golang Encode函数的具体用法?Golang Encode怎么用?Golang Encode使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Encode函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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()
}
开发者ID:Rongya,项目名称:syncthing,代码行数:35,代码来源:tls.go
示例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
}
开发者ID:vmware,项目名称:vic,代码行数:60,代码来源:setcert.go
示例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)
}
}
}
开发者ID:RadioTerminal,项目名称:podcaster,代码行数:35,代码来源:jwt.go
示例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
}
开发者ID:rawlingsj,项目名称:gofabric8,代码行数:32,代码来源:crypto.go
示例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()
}
开发者ID:jf,项目名称:gwp,代码行数:30,代码来源:gencert.go
示例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
}
开发者ID:daaku,项目名称:fakeca,代码行数:60,代码来源:fakeca.go
示例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
}
开发者ID:carriercomm,项目名称:grumble,代码行数:63,代码来源:gencert.go
示例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
}
开发者ID:pivotal-cf,项目名称:pcfdev,代码行数:33,代码来源:cert.go
示例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()
}
开发者ID:sameer2800,项目名称:nanjingtaxi,代码行数:35,代码来源:room.go
示例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
}
开发者ID:SpectoLabs,项目名称:hoverfly,代码行数:31,代码来源:certs.go
示例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()
}
开发者ID:sameer2800,项目名称:nanjingtaxi,代码行数:27,代码来源:room.go
示例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
}
开发者ID:vmware,项目名称:vic,代码行数:38,代码来源:certificate.go
示例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
}
开发者ID:MDrollette,项目名称:i2p-tools,代码行数:35,代码来源:utils.go
示例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
}
开发者ID:MDrollette,项目名称:i2p-tools,代码行数:33,代码来源:utils.go
示例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()
}
开发者ID:yexiaoming20140413,项目名称:fabio,代码行数:33,代码来源:source_test.go
示例16: GenerateSelfSignedCert
// GenerateSelfSignedCert creates a self-signed certificate and key for the given host.
// Host may be an IP or a DNS name
// The certificate will be created with file mode 0644. The key will be created with file mode 0600.
// If the certificate or key files already exist, they will be overwritten.
// Any parent directories of the certPath or keyPath will be created as needed with file mode 0755.
func GenerateSelfSignedCert(host, certPath, keyPath string) error {
priv, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return err
}
template := x509.Certificate{
SerialNumber: big.NewInt(1),
Subject: pkix.Name{
CommonName: fmt.Sprintf("%[email protected]%d", host, time.Now().Unix()),
},
NotBefore: time.Now(),
NotAfter: time.Now().Add(time.Hour * 24 * 365),
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
}
if ip := net.ParseIP(host); ip != nil {
template.IPAddresses = append(template.IPAddresses, ip)
} else {
template.DNSNames = append(template.DNSNames, host)
}
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
if err != nil {
return err
}
// Generate cert
certBuffer := bytes.Buffer{}
if err := pem.Encode(&certBuffer, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}); err != nil {
return err
}
// Generate key
keyBuffer := bytes.Buffer{}
if err := pem.Encode(&keyBuffer, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)}); err != nil {
return err
}
// Write cert
if err := os.MkdirAll(filepath.Dir(certPath), os.FileMode(0755)); err != nil {
return err
}
if err := ioutil.WriteFile(certPath, certBuffer.Bytes(), os.FileMode(0644)); err != nil {
return err
}
// Write key
if err := os.MkdirAll(filepath.Dir(keyPath), os.FileMode(0755)); err != nil {
return err
}
if err := ioutil.WriteFile(keyPath, keyBuffer.Bytes(), os.FileMode(0600)); err != nil {
return err
}
return nil
}
开发者ID:hortonworks,项目名称:kubernetes-yarn,代码行数:65,代码来源:crypto.go
示例17: GenerateCACertificate
// GenerateCACertificate generates a new certificate authority from the specified org
// and bit size and returns the certificate and key as []byte, []byte
func GenerateCACertificate(org string, bits int) ([]byte, []byte, error) {
template, err := newCertificate(org)
if err != nil {
return nil, nil, err
}
template.IsCA = true
template.KeyUsage |= x509.KeyUsageCertSign
template.KeyUsage |= x509.KeyUsageKeyEncipherment
template.KeyUsage |= x509.KeyUsageKeyAgreement
priv, err := rsa.GenerateKey(rand.Reader, bits)
if err != nil {
return nil, nil, err
}
derBytes, err := x509.CreateCertificate(rand.Reader, template, template, &priv.PublicKey, priv)
if err != nil {
return nil, nil, err
}
var certOut bytes.Buffer
var keyOut bytes.Buffer
pem.Encode(&certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
pem.Encode(&keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)})
return certOut.Bytes(), keyOut.Bytes(), nil
}
开发者ID:XuesongYang,项目名称:shipyard,代码行数:31,代码来源:tlsutils.go
示例18: RsaGenKey
// Gen RSA key pair
func RsaGenKey(filePath string, bits int) error {
if !IsDirExist(filePath) {
os.Mkdir(filePath, 0700)
}
privPath := filepath.Join(filePath, "private.pem")
pubfPath := filepath.Join(filePath, "public.pem")
if IsFileExist(privPath) || IsFileExist(pubfPath) {
log.Println("Error: files already exist at:", filePath)
return errors.New("RSA key files already exist")
}
// Gen private key
privateKey, err := rsa.GenerateKey(rand.Reader, bits)
if err != nil {
return err
}
derStream := x509.MarshalPKCS1PrivateKey(privateKey)
block := &pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: derStream,
}
file, err := os.Create(privPath)
if err != nil {
log.Println("Error: create ", privPath, " failed")
return err
}
defer file.Close()
err = pem.Encode(file, block)
if err != nil {
return err
}
file.Chmod(0400)
// Gen public key
publicKey := &privateKey.PublicKey
derPkix, err := x509.MarshalPKIXPublicKey(publicKey)
if err != nil {
return err
}
block = &pem.Block{
Type: "PUBLIC KEY",
Bytes: derPkix,
}
file, err = os.Create(pubfPath)
if err != nil {
log.Println("Error: create ", pubfPath, " failed")
return err
}
defer file.Close()
err = pem.Encode(file, block)
if err != nil {
return err
}
file.Chmod(0400)
return nil
}
开发者ID:st2py,项目名称:bitcrypt,代码行数:61,代码来源:ut_rsa.go
示例19: GenerateKey
func GenerateKey(passpharse []byte, config ConfigType) (err error) {
pubBlock, priBlock, err := _generateKey(passpharse, config)
if err != nil {
return
}
pubkeyOut, err := os.OpenFile(config.PublicKeyDir, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
if strings.EqualFold(config.PublicKeyDir, "") {
pubkeyOut = os.Stdout
} else {
return
}
}
prikeyOut, err := os.OpenFile(config.PrivateKeyDir, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
if strings.EqualFold(config.PrivateKeyDir, "") {
prikeyOut = os.Stdout
} else {
return
}
}
err = pem.Encode(pubkeyOut, pubBlock)
if err != nil {
return
}
err = pem.Encode(prikeyOut, priBlock)
return
}
开发者ID:wulinxu,项目名称:KeyAdmin-go,代码行数:31,代码来源:passwordadmin.go
示例20: GenerateCA
// GenerateCA generates a new certificate authority
// and stores the resulting certificate and key file
// in the arguments.
func GenerateCA(certFile, keyFile string) error {
log.Printf("Generating a new certificate authority.")
template := newCertificate()
template.IsCA = true
template.KeyUsage |= x509.KeyUsageCertSign
priv, err := rsa.GenerateKey(rand.Reader, RSABITS)
if err != nil {
return err
}
derBytes, err := x509.CreateCertificate(rand.Reader, template, template, &priv.PublicKey, priv)
if err != nil {
return err
}
certOut, err := os.Create(certFile)
if err != nil {
return err
}
pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
certOut.Close()
keyOut, err := os.OpenFile(keyFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return err
}
pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)})
keyOut.Close()
return nil
}
开发者ID:imdreamrunner,项目名称:generate_cert,代码行数:35,代码来源:generate_cert.go
注:本文中的encoding/pem.Encode函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论