예제 #1
0
파일: tls.go 프로젝트: Rongya/syncthing
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
0
파일: setcert.go 프로젝트: vmware/vic
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
0
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
0
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
0
파일: gencert.go 프로젝트: jf/gwp
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
0
파일: fakeca.go 프로젝트: daaku/fakeca
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
0
// 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
0
파일: cert.go 프로젝트: pivotal-cf/pcfdev
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
0
// 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
0
// 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
0
// 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
0
파일: certificate.go 프로젝트: vmware/vic
// 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
0
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
0
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
0
// 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()
}
예제 #16
0
// 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("%s@%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
}
예제 #17
0
// 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
}
예제 #18
0
파일: ut_rsa.go 프로젝트: st2py/bitcrypt
// 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
}
예제 #19
0
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
}
예제 #20
0
// 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
}
예제 #21
0
// generateFromTemplate generates a certificate from the given template and signed by
// the given parent, storing the results in a certificate and key file.
func generateFromTemplate(certFile, keyFile string, template, parent *x509.Certificate, key crypto.PrivateKey, parentKey crypto.PrivateKey) error {
	derBytes, err := x509.CreateCertificate(rand.Reader, template, parent, key.(crypto.Signer).Public(), parentKey)
	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
	}
	defer keyOut.Close()

	switch v := key.(type) {
	case *rsa.PrivateKey:
		keyBytes := x509.MarshalPKCS1PrivateKey(v)
		pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: keyBytes})
	case *ecdsa.PrivateKey:
		keyBytes, err := x509.MarshalECPrivateKey(v)
		if err != nil {
			return err
		}
		pem.Encode(keyOut, &pem.Block{Type: "EC PRIVATE KEY", Bytes: keyBytes})
	default:
		return fmt.Errorf("Unsupport private key type: %#v", key)
	}

	return nil
}
예제 #22
0
// GenerateDefaultTLS will generate a certificate and a private key, on-the-fly
// This certificate will not be persistant (until you save it yourself)
// This is made by design to generate a new certificate at each server start, if you
// don't provide one yourself
func GenerateDefaultTLS(certPath string, keyPath string) (cert []byte, key []byte) {
	log.Info("Generating TLS certificate and key")

	rootName := "itsyou.online"
	priv, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)

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

	notBefore := time.Now()
	notAfter := notBefore.Add(4 * 365 * 24 * time.Hour) // 4 years

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

	template := x509.Certificate{
		SerialNumber: serialNumber,
		Subject: pkix.Name{
			Country:      []string{"Belgium"},
			Locality:     []string{"Lochristi"},
			Organization: []string{"It's You Online"},
			CommonName:   rootName,
		},
		NotBefore: notBefore,
		NotAfter:  notAfter,

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

		DNSNames: []string{rootName},
	}

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

	// Certificates output (in memory)

	var certOut, keyOut bytes.Buffer

	pem.Encode(&certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})

	b, err := x509.MarshalECPrivateKey(priv)
	if err != nil {
		log.Panic("Unable to marshal ECDSA private key: ", err)
	}

	pemUnmarsh := pem.Block{Type: "EC PRIVATE KEY", Bytes: b}

	pem.Encode(&keyOut, &pemUnmarsh)

	return certOut.Bytes(), keyOut.Bytes()
}
예제 #23
0
파일: genprodcerts.go 프로젝트: Debian/dcs
func generatecert() error {
	priv, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		return fmt.Errorf("failed to generate private key: %s", err)
	}

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

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

	template := x509.Certificate{
		SerialNumber: serialNumber,
		Subject: pkix.Name{
			Organization: []string{"Debian Code Search"},
		},
		DNSNames: []string{
			"localhost",
			"monitoring.rackspace.zekjur.net",
			"int-dcsi-web.rackspace.zekjur.net",
			"int-dcsi-index-0.rackspace.zekjur.net",
			"int-dcsi-index-1.rackspace.zekjur.net",
			"int-dcsi-index-2.rackspace.zekjur.net",
			"int-dcsi-index-3.rackspace.zekjur.net",
			"int-dcsi-index-4.rackspace.zekjur.net",
			"int-dcsi-index-5.rackspace.zekjur.net",
		},
		NotBefore: notBefore,
		NotAfter:  notAfter,

		KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
		IsCA:     true,
		BasicConstraintsValid: true,
	}

	derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
	if err != nil {
		return fmt.Errorf("Failed to create certificate: %s", err)
	}

	certOut, err := os.Create("prod-cert.pem")
	if err != nil {
		return fmt.Errorf("failed to open prod-cert.pem for writing: %s", err)
	}
	pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
	certOut.Close()

	keyOut, err := os.OpenFile("prod-key.pem", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
	if err != nil {
		return fmt.Errorf("failed to open prod-key.pem for writing:", err)
	}
	pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)})
	keyOut.Close()
	return nil
}
예제 #24
0
파일: rootca.go 프로젝트: nonovc/goproxy
func (c *RootCA) issue(commonName string, vaildFor time.Duration, rsaBits int) error {
	certFile := c.toFilename(commonName, ".crt")

	csrTemplate := &x509.CertificateRequest{
		Signature: []byte(commonName),
		Subject: pkix.Name{
			Country:            []string{"CN"},
			Organization:       []string{commonName},
			OrganizationalUnit: []string{c.name},
			CommonName:         commonName,
		},
		SignatureAlgorithm: x509.SHA256WithRSA,
	}

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

	csrBytes, err := x509.CreateCertificateRequest(rand.Reader, csrTemplate, priv)
	if err != nil {
		return err
	}

	csr, err := x509.ParseCertificateRequest(csrBytes)
	if err != nil {
		return err
	}

	certTemplate := &x509.Certificate{
		Subject:            csr.Subject,
		PublicKeyAlgorithm: csr.PublicKeyAlgorithm,
		PublicKey:          csr.PublicKey,
		SerialNumber:       big.NewInt(time.Now().UnixNano()),
		SignatureAlgorithm: x509.SHA256WithRSA,
		NotBefore:          time.Now().Add(-time.Duration(10 * time.Minute)).UTC(),
		NotAfter:           time.Now().Add(vaildFor),
		KeyUsage:           x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
		ExtKeyUsage: []x509.ExtKeyUsage{
			x509.ExtKeyUsageServerAuth,
			x509.ExtKeyUsageClientAuth,
		},
	}

	certBytes, err := x509.CreateCertificate(rand.Reader, certTemplate, c.ca, csr.PublicKey, c.priv)
	if err != nil {
		return err
	}

	outFile, err := os.Create(certFile)
	defer outFile.Close()
	if err != nil {
		return err
	}
	pem.Encode(outFile, &pem.Block{Type: "CERTIFICATE", Bytes: certBytes})
	pem.Encode(outFile, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)})

	return nil
}
예제 #25
0
파일: cert.go 프로젝트: containerx/machine
// GenerateCert generates a new certificate signed using the provided
// certificate authority files and stores the result in the certificate
// file and key provided.  The provided host names are set to the
// appropriate certificate fields.
func (xcg *X509CertGenerator) GenerateCert(hosts []string, certFile, keyFile, caFile, caKeyFile, org string, bits int) error {
	template, err := xcg.newCertificate(org)
	if err != nil {
		return err
	}
	// client
	if len(hosts) == 1 && hosts[0] == "" {
		template.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}
		template.KeyUsage = x509.KeyUsageDigitalSignature
	} else { // server
		template.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth}
		for _, h := range hosts {
			if ip := net.ParseIP(h); ip != nil {
				template.IPAddresses = append(template.IPAddresses, ip)
			} else {
				template.DNSNames = append(template.DNSNames, h)
			}
		}
	}

	tlsCert, err := tls.LoadX509KeyPair(caFile, caKeyFile)
	if err != nil {
		return err
	}

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

	x509Cert, err := x509.ParseCertificate(tlsCert.Certificate[0])
	if err != nil {
		return err
	}

	derBytes, err := x509.CreateCertificate(rand.Reader, template, x509Cert, &priv.PublicKey, tlsCert.PrivateKey)
	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
}
예제 #26
0
파일: tls.go 프로젝트: micro/misc
func Certificate(host ...string) (tls.Certificate, error) {
	priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		return tls.Certificate{}, err
	}

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

	serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
	serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
	if err != nil {
		return tls.Certificate{}, err
	}

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

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

	for _, h := range host {
		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 {
		return tls.Certificate{}, err
	}

	// create public key
	certOut := bytes.NewBuffer(nil)
	pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})

	// create private key
	keyOut := bytes.NewBuffer(nil)
	b, err := x509.MarshalECPrivateKey(priv)
	if err != nil {
		return tls.Certificate{}, err
	}
	pem.Encode(keyOut, &pem.Block{Type: "EC PRIVATE KEY", Bytes: b})

	return tls.X509KeyPair(certOut.Bytes(), keyOut.Bytes())
}
예제 #27
0
// generateRSACerts generates a basic self signed certificate using a key length
// of rsaBits, valid for validFor time.
func generateRSACerts(host string, isCA bool, keyOut, certOut io.Writer) error {
	if len(host) == 0 {
		return fmt.Errorf("Require a non-empty host for client hello")
	}
	priv, err := rsa.GenerateKey(rand.Reader, rsaBits)
	if err != nil {
		return fmt.Errorf("Failed to generate key: %v", err)
	}
	notBefore := time.Now()
	notAfter := notBefore.Add(validFor)

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

	if err != nil {
		return fmt.Errorf("failed to generate serial number: %s", err)
	}
	template := x509.Certificate{
		SerialNumber: serialNumber,
		Subject: pkix.Name{
			CommonName:   "default",
			Organization: []string{"Acme Co"},
		},
		NotBefore: notBefore,
		NotAfter:  notAfter,

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

	hosts := strings.Split(host, ",")
	for _, h := range hosts {
		if ip := net.ParseIP(h); ip != nil {
			template.IPAddresses = append(template.IPAddresses, ip)
		} else {
			template.DNSNames = append(template.DNSNames, h)
		}
	}

	if isCA {
		template.IsCA = true
		template.KeyUsage |= x509.KeyUsageCertSign
	}

	derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
	if err != nil {
		return fmt.Errorf("Failed to create certificate: %s", err)
	}
	if err := pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}); err != nil {
		return fmt.Errorf("Failed creating cert: %v", err)
	}
	if err := pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)}); err != nil {
		return fmt.Errorf("Failed creating keay: %v", err)
	}
	return nil
}
예제 #28
0
파일: fakeca.go 프로젝트: daaku/fakeca
func (g *Generator) genRootCA() error {
	certFileName := g.certFileName()
	keyFileName := g.keyFileName()

	if _, err := os.Stat(certFileName); !os.IsNotExist(err) {
		return stackerr.Newf("%s must not exist", certFileName)
	}
	if _, err := os.Stat(keyFileName); !os.IsNotExist(err) {
		return stackerr.Newf("%s must not exist", keyFileName)
	}

	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: g.RootName,
		},
		NotBefore:             now.Add(-5 * time.Minute).UTC(),
		NotAfter:              now.Add(g.MaxAge),
		IsCA:                  true,
		SubjectKeyId:          []byte{1, 2, 3, 4},
		KeyUsage:              x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
		BasicConstraintsValid: true,
	}

	derBytes, err := x509.CreateCertificate(
		rand.Reader, &template, &template, &priv.PublicKey, priv)
	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
}
예제 #29
0
파일: tls.go 프로젝트: kattunga/syncthing
func newCertificate(certFile, keyFile, name string) (tls.Certificate, error) {
	l.Infof("Generating RSA key and certificate for %s...", name)

	priv, err := rsa.GenerateKey(rand.Reader, tlsRSABits)
	if err != nil {
		l.Fatalln("generate key:", 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: name,
		},
		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)
	if err != nil {
		l.Fatalln("create cert:", err)
	}

	certOut, err := os.Create(certFile)
	if err != nil {
		l.Fatalln("save cert:", err)
	}
	err = pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
	if err != nil {
		l.Fatalln("save cert:", err)
	}
	err = certOut.Close()
	if err != nil {
		l.Fatalln("save cert:", err)
	}

	keyOut, err := os.OpenFile(keyFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
	if err != nil {
		l.Fatalln("save key:", err)
	}
	err = pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)})
	if err != nil {
		l.Fatalln("save key:", err)
	}
	err = keyOut.Close()
	if err != nil {
		l.Fatalln("save key:", err)
	}

	return tls.LoadX509KeyPair(certFile, keyFile)
}
예제 #30
0
파일: tls.go 프로젝트: Collinux/snap
func generateCert(t *tls) error {
	// good for 1 year
	notBefore := time.Now()
	notAfter := notBefore.Add(time.Hour * 24 * 365)

	serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
	serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
	if err != nil {
		return err
	}

	temp := &x509.Certificate{
		SerialNumber: serialNumber,
		Subject: pkix.Name{
			Organization: []string{"Local snap Agent"},
		},
		DNSNames:              []string{"localhost"},
		NotBefore:             notBefore,
		NotAfter:              notAfter,
		KeyUsage:              x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
		ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
		BasicConstraintsValid: true,
	}

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

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

	certPath := os.TempDir() + "/cert.pem"
	keyPath := os.TempDir() + "/key.pem"

	cout, err := os.Create(certPath)
	if err != nil {
		return err
	}
	pem.Encode(cout, &pem.Block{Type: "CERTIFICATE", Bytes: cbytes})
	cout.Close()

	kout, err := os.OpenFile(keyPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
	if err != nil {
		return err
	}
	pem.Encode(kout, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)})
	kout.Close()

	t.cert = certPath
	t.key = keyPath

	return nil
}