Example #1
0
File: main.go Project: cvvs/csrtool
func newCSR(key crypto.PrivateKey) ([]byte, error) {
	subject := pkix.Name{Country: []string{country}, Province: []string{stateProvince}, Locality: []string{locality},
		Organization: []string{org}, OrganizationalUnit: []string{orgUnit}, CommonName: flag.Args()[0]}

	template := x509.CertificateRequest{Subject: subject, DNSNames: flag.Args()}
	return x509.CreateCertificateRequest(rand.Reader, &template, key)
}
func TestCertificateKeyNotEqualAccountKey(t *testing.T) {
	_, _, sa, ra, cleanUp := initAuthorities(t)
	defer cleanUp()
	authz := core.Authorization{}
	authz, _ = sa.NewPendingAuthorization(authz)
	authz.Identifier = core.AcmeIdentifier{
		Type:  core.IdentifierDNS,
		Value: "www.example.com",
	}
	csr := x509.CertificateRequest{
		SignatureAlgorithm: x509.SHA256WithRSA,
		PublicKey:          AccountKeyA.Key,
		DNSNames:           []string{"www.example.com"},
	}
	csrBytes, err := x509.CreateCertificateRequest(rand.Reader, &csr, AccountPrivateKey.Key)
	test.AssertNotError(t, err, "Failed to sign CSR")
	parsedCSR, err := x509.ParseCertificateRequest(csrBytes)
	test.AssertNotError(t, err, "Failed to parse CSR")
	sa.UpdatePendingAuthorization(authz)
	sa.FinalizeAuthorization(authz)
	certRequest := core.CertificateRequest{
		CSR: parsedCSR,
	}

	// Registration id 1 has key == AccountKeyA
	_, err = ra.NewCertificate(certRequest, 1)
	test.AssertError(t, err, "Should have rejected cert with key = account key")
	test.AssertEquals(t, err.Error(), "Certificate public key must be different than account key")

	t.Log("DONE TestCertificateKeyNotEqualAccountKey")
}
Example #3
0
// MakeCSR generates a PEM-encoded CSR using the supplied private key, subject, and SANs.
// All key types that are implemented via crypto.Signer are supported (This includes *rsa.PrivateKey and *ecdsa.PrivateKey.)
func MakeCSR(privateKey interface{}, subject *pkix.Name, dnsSANs []string, ipSANs []net.IP) (csr []byte, err error) {
	// Customize the signature for RSA keys, depending on the key size
	var sigType x509.SignatureAlgorithm
	if privateKey, ok := privateKey.(*rsa.PrivateKey); ok {
		keySize := privateKey.N.BitLen()
		switch {
		case keySize >= 4096:
			sigType = x509.SHA512WithRSA
		case keySize >= 3072:
			sigType = x509.SHA384WithRSA
		default:
			sigType = x509.SHA256WithRSA
		}
	}

	template := &x509.CertificateRequest{
		Subject:            *subject,
		SignatureAlgorithm: sigType,
		DNSNames:           dnsSANs,
		IPAddresses:        ipSANs,
	}

	csr, err = x509.CreateCertificateRequest(cryptorand.Reader, template, privateKey)
	if err != nil {
		return nil, err
	}

	csrPemBlock := &pem.Block{
		Type:  "CERTIFICATE REQUEST",
		Bytes: csr,
	}

	return pem.EncodeToMemory(csrPemBlock), nil
}
Example #4
0
func (r *reconcile) createCSR(t *storage.Target) ([]byte, error) {
	csr := &x509.CertificateRequest{
		DNSNames: t.Request.Names,
	}

	if t.Request.OCSPMustStaple {
		csr.Extensions = append(csr.Extensions, pkix.Extension{
			Id:    oidTLSFeature,
			Value: mustStapleFeatureValue,
		})
	}

	pk, err := r.generateOrGetKey(&t.Request.Key)
	if err != nil {
		log.Errore(err, "could not generate key while generating CSR for %v", t)
		return nil, err
	}

	_, err = r.store.ImportKey(pk)
	if err != nil {
		log.Errore(err, "could not import freshly generated key while generating CSR for %v", t)
		return nil, err
	}

	csr.SignatureAlgorithm, err = signatureAlgorithmFromKey(pk)
	if err != nil {
		return nil, err
	}

	return x509.CreateCertificateRequest(rand.Reader, csr, pk)
}
Example #5
0
func newCSR(domain string, bits int) (*x509.CertificateRequest, *rsa.PrivateKey, error) {
	l := log.WithField("domain", domain)

	l.Infof("Generating %d-bit RSA key", bits)
	certKey, err := rsa.GenerateKey(rand.Reader, bits)
	if err != nil {
		return nil, nil, err
	}

	template := &x509.CertificateRequest{
		SignatureAlgorithm: x509.SHA256WithRSA,
		PublicKeyAlgorithm: x509.RSA,
		PublicKey:          &certKey.PublicKey,
		Subject:            pkix.Name{CommonName: domain},
		DNSNames:           []string{domain},
	}

	l.Debugln("Generating CSR")
	csrDER, err := x509.CreateCertificateRequest(rand.Reader, template, certKey)
	if err != nil {
		return nil, nil, err
	}

	csr, err := x509.ParseCertificateRequest(csrDER)
	if err != nil {
		return nil, nil, err
	}
	return csr, certKey, nil
}
func main() {
	block, _ := pem.Decode([]byte(rsaPrivateKey))
	rsaPriv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		log.Fatalf("Failed to parse private key: %s", err)
	}

	req := &x509.CertificateRequest{
		Subject: pkix.Name{
			CommonName: "CapiTalizedLetters.com",
		},
		DNSNames: []string{
			"moreCAPs.com",
			"morecaps.com",
			"evenMOREcaps.com",
			"Capitalizedletters.COM",
		},
	}
	csr, err := x509.CreateCertificateRequest(rand.Reader, req, rsaPriv)
	if err != nil {
		log.Fatalf("unable to create CSR: %s", err)
	}
	_, err = os.Stdout.Write(csr)
	if err != nil {
		log.Fatalf("unable to write to stdout: %s", err)
	}
}
Example #7
0
// CreateCertificateRequest generates a new certificate request
func CreateCertificateRequest(logger log.Logger, key *rsa.PrivateKey, name, org, country, hostList string) (*x509.CertificateRequest, []byte, error) {

	// Create template
	logger.Info("Creating Certificate template")
	template := &x509.CertificateRequest{
		Subject: pkix.Name{
			Country:            []string{country},
			Organization:       []string{org},
			OrganizationalUnit: []string{name},
		},
	}

	// Associate hosts
	logger.Info("Adding Hosts to Certificate")
	hosts := strings.Split(hostList, ",")
	for _, h := range hosts {
		if ip := net.ParseIP(h); ip != nil {
			template.IPAddresses = append(template.IPAddresses, ip)
		} else {
			template.DNSNames = append(template.DNSNames, h)
		}
	}

	// Create cert
	logger.Info("Generating Certificate")
	cert, err := x509.CreateCertificateRequest(rand.Reader, template, key)
	if err != nil {
		return nil, nil, err
	}

	return template, cert, nil
}
Example #8
0
// signWithCSR creates a new root certificate from signing a X509.CertificateRequest
// by a crypto.Signer.
func signWithCSR(tpl *x509.CertificateRequest, priv crypto.Signer, policy *config.Signing) (cert, csrPEM []byte, err error) {
	if policy == nil {
		policy = CAPolicy()
	}
	csrPEM, err = x509.CreateCertificateRequest(rand.Reader, tpl, priv)
	if err != nil {
		log.Errorf("failed to generate a CSR: %v", err)
		// The use of CertificateError was a matter of some
		// debate; it is the one edge case in which a new
		// error category specifically for CSRs might be
		// useful, but it was deemed that one edge case did
		// not a new category justify.
		err = cferr.Wrap(cferr.CertificateError, cferr.BadRequest, err)
		return
	}

	p := &pem.Block{
		Type:  "CERTIFICATE REQUEST",
		Bytes: csrPEM,
	}
	csrPEM = pem.EncodeToMemory(p)

	s, err := local.NewSigner(priv, nil, signer.DefaultSigAlgo(priv), nil)
	if err != nil {
		log.Errorf("failed to create signer: %v", err)
		return
	}
	s.SetPolicy(policy)

	signReq := signer.SignRequest{Request: string(csrPEM)}
	cert, err = s.Sign(signReq)
	return
}
Example #9
0
// certRequest creates a certificate request for the given common name cn
// and optional SANs.
func certRequest(key crypto.Signer, cn string, san ...string) ([]byte, error) {
	req := &x509.CertificateRequest{
		Subject:  pkix.Name{CommonName: cn},
		DNSNames: san,
	}
	return x509.CreateCertificateRequest(rand.Reader, req, key)
}
Example #10
0
func (this *Csr) ToCsr() {
	data := &x509.CertificateRequest{}
	data.Subject.Country = []string{
		this.Country,
	}
	data.Subject.Province = []string{
		this.State,
	}
	data.Subject.Locality = []string{
		this.Locality,
	}
	if len(this.OrganizationalName) > 0 {
		data.Subject.Organization = []string{
			this.OrganizationalName,
		}
	}
	if len(this.OrganizationalUnit) > 0 {
		data.Subject.OrganizationalUnit = []string{
			this.OrganizationalUnit,
		}
	}
	data.Subject.CommonName = this.CommonName

	if this.CsrAlgorithm == "sha256" {
		data.SignatureAlgorithm = x509.SHA256WithRSA
	} else {
		data.SignatureAlgorithm = x509.SHA1WithRSA
	}

	data.Signature = this.priv

	this.csr, _ = x509.CreateCertificateRequest(rand.Reader, data, this.privRsa)

	this.CsrString = CSR_PREFIX + "\n" + this.keyTo(this.csr) + "\n" + CSR_SUFFIX
}
Example #11
0
// CreateCertificateSigningRequest sets up a request to create a csr file with the given parameters
func CreateCertificateSigningRequest(key *Key, organizationalUnit string, ipList []net.IP, domainList []string, organization string, country string, province string, locality string, commonName string) (*CertificateSigningRequest, error) {

	csrPkixName.CommonName = commonName

	if len(organizationalUnit) > 0 {
		csrPkixName.OrganizationalUnit = []string{organizationalUnit}
	}
	if len(organization) > 0 {
		csrPkixName.Organization = []string{organization}
	}
	if len(country) > 0 {
		csrPkixName.Country = []string{country}
	}
	if len(province) > 0 {
		csrPkixName.Province = []string{province}
	}
	if len(locality) > 0 {
		csrPkixName.Locality = []string{locality}
	}
	csrTemplate := &x509.CertificateRequest{
		Subject:     csrPkixName,
		IPAddresses: ipList,
		DNSNames:    domainList,
	}

	csrBytes, err := x509.CreateCertificateRequest(rand.Reader, csrTemplate, key.Private)
	if err != nil {
		return nil, err
	}
	return NewCertificateSigningRequestFromDER(csrBytes), nil
}
Example #12
0
File: csr.go Project: bbandix/cfssl
// Generate creates a new CSR from a CertificateRequest structure and
// an existing key. The KeyRequest field is ignored.
func Generate(priv crypto.Signer, req *CertificateRequest) (csr []byte, err error) {
	sigAlgo := helpers.SignerAlgo(priv, crypto.SHA256)
	if sigAlgo == x509.UnknownSignatureAlgorithm {
		return nil, cferr.New(cferr.PrivateKeyError, cferr.Unavailable)
	}

	var tpl = x509.CertificateRequest{
		Subject:            req.Name(),
		SignatureAlgorithm: sigAlgo,
	}

	for i := range req.Hosts {
		if ip := net.ParseIP(req.Hosts[i]); ip != nil {
			tpl.IPAddresses = append(tpl.IPAddresses, ip)
		} else {
			tpl.DNSNames = append(tpl.DNSNames, req.Hosts[i])
		}
	}

	csr, err = x509.CreateCertificateRequest(rand.Reader, &tpl, priv)
	if err != nil {
		log.Errorf("failed to generate a CSR: %v", err)
		err = cferr.Wrap(cferr.CSRError, cferr.BadRequest, err)
		return
	}
	block := pem.Block{
		Type:  "CERTIFICATE REQUEST",
		Bytes: csr,
	}

	log.Info("encoded CSR")
	csr = pem.EncodeToMemory(&block)
	return
}
Example #13
0
func CreateCertificateSigningRequest(key *Key, name string, ip_list string, domain_list string, organization string, country string) (*CertificateSigningRequest, error) {
	// Sanity check on the ip values
	ips, err := ParseAndValidateIPs(ip_list)
	if err != nil {
		return nil, err
	}

	domains := strings.Split(domain_list, ",")
	if domain_list == "" {
		domains = nil
	}

	csrPkixName.OrganizationalUnit = []string{name}
	if len(domains) != 0 {
		csrPkixName.CommonName = domains[0]
	} else if len(ips) != 0 {
		csrPkixName.CommonName = ips[0].String()
	} else {
		return nil, errors.New("no valided domain nor ip provided")
	}
	csrPkixName.Organization = []string{organization}
	csrPkixName.Country = []string{country}
	csrTemplate := &x509.CertificateRequest{
		Subject:     csrPkixName,
		IPAddresses: ips,
		DNSNames:    domains,
	}

	csrBytes, err := x509.CreateCertificateRequest(rand.Reader, csrTemplate, key.Private)
	if err != nil {
		return nil, err
	}
	return NewCertificateSigningRequestFromDER(csrBytes), nil
}
Example #14
0
// Creates a certificate signing request for the specified FQDN. Defaults to SHA256WithRSA.
func MakeCertSignReq(fqdn string) []byte {
	// Populate the subject data.
	subject := pkix.Name{
		Country:            []string{"US"},
		Organization:       []string{"Microfocus International"},
		OrganizationalUnit: []string{"Identity and Access Management"},
		Locality:           []string{"Provo"},
		Province:           []string{"Utah"},
		CommonName:         fqdn,
	}

	// Populate the cert request template.
	certificateRequest := &x509.CertificateRequest{
		Subject:            subject,
		SignatureAlgorithm: 4,
		DNSNames:           []string{fqdn},
		EmailAddresses:     []string{"*****@*****.**"},
	}

	// Create a private key.
	privatekey, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		fmt.Println(err)
	}

	// Create signing request and return byte slice if no errors were encountered.
	certSignReq, err := x509.CreateCertificateRequest(rand.Reader, certificateRequest, privatekey)
	if err != nil {
		fmt.Println(err)
	}
	return certSignReq
}
Example #15
0
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
}
Example #16
0
func generateCsr(privateKey *rsa.PrivateKey, domain string) ([]byte, error) {
	template := x509.CertificateRequest{
		Subject: pkix.Name{
			CommonName: domain,
		},
	}

	return x509.CreateCertificateRequest(rand.Reader, &template, privateKey)
}
Example #17
0
File: csr.go Project: bbandix/cfssl
// Regenerate uses the provided CSR as a template for signing a new
// CSR using priv.
func Regenerate(priv crypto.Signer, csr []byte) ([]byte, error) {
	req, extra, err := helpers.ParseCSR(csr)
	if err != nil {
		return nil, err
	} else if len(extra) > 0 {
		return nil, errors.New("csr: trailing data in certificate request")
	}

	return x509.CreateCertificateRequest(rand.Reader, req, priv)
}
func CreateCertRequest(d *schema.ResourceData, meta interface{}) error {
	keyAlgoName := d.Get("key_algorithm").(string)
	var keyFunc keyParser
	var ok bool
	if keyFunc, ok = keyParsers[keyAlgoName]; !ok {
		return fmt.Errorf("invalid key_algorithm %#v", keyAlgoName)
	}
	keyBlock, _ := pem.Decode([]byte(d.Get("private_key_pem").(string)))
	if keyBlock == nil {
		return fmt.Errorf("no PEM block found in private_key_pem")
	}
	key, err := keyFunc(keyBlock.Bytes)
	if err != nil {
		return fmt.Errorf("failed to decode private_key_pem: %s", err)
	}

	subjectConfs := d.Get("subject").([]interface{})
	if len(subjectConfs) != 1 {
		return fmt.Errorf("must have exactly one 'subject' block")
	}
	subjectConf := subjectConfs[0].(map[string]interface{})
	subject, err := nameFromResourceData(subjectConf)
	if err != nil {
		return fmt.Errorf("invalid subject block: %s", err)
	}

	certReq := x509.CertificateRequest{
		Subject: *subject,
	}

	dnsNamesI := d.Get("dns_names").([]interface{})
	for _, nameI := range dnsNamesI {
		certReq.DNSNames = append(certReq.DNSNames, nameI.(string))
	}
	ipAddressesI := d.Get("ip_addresses").([]interface{})
	for _, ipStrI := range ipAddressesI {
		ip := net.ParseIP(ipStrI.(string))
		if ip == nil {
			return fmt.Errorf("invalid IP address %#v", ipStrI.(string))
		}
		certReq.IPAddresses = append(certReq.IPAddresses, ip)
	}

	certReqBytes, err := x509.CreateCertificateRequest(rand.Reader, &certReq, key)
	if err != nil {
		fmt.Errorf("Error creating certificate request: %s", err)
	}
	certReqPem := string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE REQUEST", Bytes: certReqBytes}))

	d.SetId(hashForState(string(certReqBytes)))
	d.Set("cert_request_pem", certReqPem)

	return nil
}
Example #19
0
// NewRequest returns a new x509 signing request based on the provided template
func NewRequest(priv *Key, template *x509.CertificateRequest) (*Request, error) {
	derBytes, err := x509.CreateCertificateRequest(rand.Reader, template, priv.PrivateKey)
	if err != nil {
		return nil, err
	}

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

	return &Request{csr}, nil
}
Example #20
0
func generateCsr(privateKey crypto.PrivateKey, domain string, san []string) ([]byte, error) {
	template := x509.CertificateRequest{
		Subject: pkix.Name{
			CommonName: domain,
		},
	}

	if len(san) > 0 {
		template.DNSNames = san
	}

	return x509.CreateCertificateRequest(rand.Reader, &template, privateKey)
}
Example #21
0
File: main.go Project: yahoo/coname
func main() {
	// This script generates CSR, private key and a verifier ID.
	// Keyserver admin will sign the CSR and provide the cert
	privKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		panic(err)
	}
	pk, sk, err := ed25519.GenerateKey(rand.Reader)
	if err != nil {
		panic(err)
	}
	sv := &proto.PublicKey{PubkeyType: &proto.PublicKey_Ed25519{Ed25519: pk[:]}}
	hostname := fmt.Sprintf("verifier %x", proto.KeyID(sv))
	fmt.Println("verifier ID: " + hostname + "\nID(uint): " + strconv.FormatUint(proto.KeyID(sv), 10))
	err = ioutil.WriteFile("signing.ed25519secret", []byte(sk[:]), 0644)
	if err != nil {
		panic(err)
	}

	certTemplate := &x509.CertificateRequest{
		Subject: pkix.Name{CommonName: hostname},
	}
	csrDER, err := x509.CreateCertificateRequest(rand.Reader, certTemplate, privKey)
	if err != nil {
		panic(err)
	}
	csrPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE REQUEST", Bytes: csrDER})
	// openssl req -in csr.pem -noout -text
	err = ioutil.WriteFile("csr.pem", csrPEM, 0644)
	if err != nil {
		panic(err)
	}
	keyF, err := os.OpenFile("key.pem", os.O_WRONLY|os.O_CREATE, 0644)
	defer keyF.Close()
	if err != nil {
		panic(err)
	}
	skDer, err := x509.MarshalECPrivateKey(privKey)
	if err != nil {
		panic(err)
	}
	err = pem.Encode(keyF, &pem.Block{
		Type:    "EC PRIVATE KEY",
		Headers: make(map[string]string),
		Bytes:   skDer,
	})
	if err != nil {
		panic(err)
	}

}
Example #22
0
func mustGenerateTestCSR() []byte {
	cr := &x509.CertificateRequest{
		Subject: pkix.Name{
			CommonName: "a.example.com",
		},
		DNSNames: []string{"b.example.com"},
	}
	csr, err := x509.CreateCertificateRequest(rand.Reader, cr, testJWK.Key)
	if err != nil {
		panic(fmt.Errorf("x509.CreateCertificateRequest failed: %v", err))
	}

	return csr
}
Example #23
0
func TestDeniedCSR(t *testing.T) {
	key, _ := rsa.GenerateKey(rand.Reader, 512)
	template := &x509.CertificateRequest{
		Subject:  pkix.Name{CommonName: "google.com"},
		DNSNames: []string{"badguys.com", "reallybad.com"},
	}
	csrBytes, _ := x509.CreateCertificateRequest(rand.Reader, template, key)
	csr, _ := x509.ParseCertificateRequest(csrBytes)

	sa := initSA(t)
	exists, err := sa.AlreadyDeniedCSR(append(csr.DNSNames, csr.Subject.CommonName))
	test.AssertNotError(t, err, "AlreadyDeniedCSR failed")
	test.Assert(t, !exists, "Found non-existent CSR")
}
Example #24
0
File: csr.go Project: spxtr/contrib
// NewCertificateRequest generates a PEM-encoded CSR using the supplied private key, subject, and SANs.
// privateKey must be a *ecdsa.PrivateKey or *rsa.PrivateKey.
func NewCertificateRequest(privateKey interface{}, subject *pkix.Name, dnsSANs []string, ipSANs []net.IP) (csr []byte, err error) {
	var sigType x509.SignatureAlgorithm

	switch privateKey := privateKey.(type) {
	case *ecdsa.PrivateKey:
		switch privateKey.Curve {
		case elliptic.P224(), elliptic.P256():
			sigType = x509.ECDSAWithSHA256
		case elliptic.P384():
			sigType = x509.ECDSAWithSHA384
		case elliptic.P521():
			sigType = x509.ECDSAWithSHA512
		default:
			return nil, fmt.Errorf("unknown elliptic curve: %v", privateKey.Curve)
		}
	case *rsa.PrivateKey:
		keySize := privateKey.N.BitLen()
		switch {
		case keySize >= 4096:
			sigType = x509.SHA512WithRSA
		case keySize >= 3072:
			sigType = x509.SHA384WithRSA
		default:
			sigType = x509.SHA256WithRSA
		}

	default:
		return nil, fmt.Errorf("unsupported key type: %T", privateKey)
	}

	template := &x509.CertificateRequest{
		Subject:            *subject,
		SignatureAlgorithm: sigType,
		DNSNames:           dnsSANs,
		IPAddresses:        ipSANs,
	}

	csr, err = x509.CreateCertificateRequest(cryptorand.Reader, template, privateKey)
	if err != nil {
		return nil, err
	}

	csrPemBlock := &pem.Block{
		Type:  "CERTIFICATE REQUEST",
		Bytes: csr,
	}

	return pem.EncodeToMemory(csrPemBlock), nil
}
Example #25
0
func (s *Store) createCSR(t *Target) ([]byte, error) {
	csr := &x509.CertificateRequest{
		DNSNames: t.Request.Names,
	}

	pk, _, err := s.createNewCertKey()
	if err != nil {
		return nil, err
	}

	csr.SignatureAlgorithm, err = signatureAlgorithmFromKey(pk)
	if err != nil {
		return nil, err
	}

	return x509.CreateCertificateRequest(rand.Reader, csr, pk)
}
func CreateCertRequest(d *schema.ResourceData, meta interface{}) error {
	key, err := parsePrivateKey(d, "private_key_pem", "key_algorithm")
	if err != nil {
		return err
	}

	subjectConfs := d.Get("subject").([]interface{})
	if len(subjectConfs) != 1 {
		return fmt.Errorf("must have exactly one 'subject' block")
	}
	subjectConf := subjectConfs[0].(map[string]interface{})
	subject, err := nameFromResourceData(subjectConf)
	if err != nil {
		return fmt.Errorf("invalid subject block: %s", err)
	}

	certReq := x509.CertificateRequest{
		Subject: *subject,
	}

	dnsNamesI := d.Get("dns_names").([]interface{})
	for _, nameI := range dnsNamesI {
		certReq.DNSNames = append(certReq.DNSNames, nameI.(string))
	}
	ipAddressesI := d.Get("ip_addresses").([]interface{})
	for _, ipStrI := range ipAddressesI {
		ip := net.ParseIP(ipStrI.(string))
		if ip == nil {
			return fmt.Errorf("invalid IP address %#v", ipStrI.(string))
		}
		certReq.IPAddresses = append(certReq.IPAddresses, ip)
	}

	certReqBytes, err := x509.CreateCertificateRequest(rand.Reader, &certReq, key)
	if err != nil {
		fmt.Errorf("Error creating certificate request: %s", err)
	}
	certReqPem := string(pem.EncodeToMemory(&pem.Block{Type: pemCertReqType, Bytes: certReqBytes}))

	d.SetId(hashForState(string(certReqBytes)))
	d.Set("cert_request_pem", certReqPem)

	return nil
}
Example #27
0
func main() {
	// Parsing command line flags
	rsaBits := flag.Int("bits", 2048, "Size of RSA key to generate.")
	crtCountry := flag.String("C", "DE", "Subject Country")
	crtState := flag.String("ST", "Nordrhein-Westfalen", "Subject Country")
	crtLocation := flag.String("L", "Guetersloh", "Subject Location")
	crtOrganization := flag.String("O", "arvato Systems GmbH", "Subject Organization")
	crtOrganizationalUnit := flag.String("OU", "Application Services", "Subject Organizational Unit")
	crtCommonName := flag.String("CN", "*.arvato-systems.de", "Subject Common Name")
	crtSAN := flag.String("SAN", "*.arvato-systems.de,arvato-systems.de", "Subject alternative Names")
	flag.Parse()

	// Generating private key
	privateKey, err := rsa.GenerateKey(rand.Reader, *rsaBits)
	if err != nil {
		fmt.Println(err)
	}

	// Format the key for output
	//	keyFile, err := os.OpenFile(logfile, os.O_RDWR | os.O_CREATE | os.O_APPEND, 0666)
	keyOutput := os.Stdout
	pem.Encode(keyOutput, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)})

	template := &x509.CertificateRequest{
		Subject: pkix.Name{
			CommonName:         *crtCommonName,
			Country:            []string{"AU"},
			Province:           []string{"Some-State"},
			Locality:           []string{"MyCity"},
			Organization:       []string{"Company Ltd"},
			OrganizationalUnit: []string{"IT"},
		},
		EmailAddresses: []string{"*****@*****.**"},
		DNSNames:       []string{"example.abc123.com"},
	}

	certCSR, err := x509.CreateCertificateRequest(rand.Reader, template, privateKey)
	if err != nil {
		fmt.Println(err)
	}
	//	pem.Encode(os.Stdout, &pem.Block{Type: "CERTIFICATE REQUEST", Bytes: csrBytes})
	//	pem.Encode(os.Stdout,
	//fmt.Println(keyBytes)
}
Example #28
0
func newCSR(serverKey *rsa.PrivateKey) (*x509.CertificateRequest, error) {
	template := &x509.CertificateRequest{
		SignatureAlgorithm: x509.SHA256WithRSA,
		PublicKeyAlgorithm: x509.RSA,
		PublicKey:          &serverKey.PublicKey,
		Subject:            pkix.Name{CommonName: *reachableHost},
		DNSNames:           []string{*reachableHost},
	}
	csrDER, err := x509.CreateCertificateRequest(
		rand.Reader, template, serverKey)
	if err != nil {
		return nil, err
	}
	csr, err := x509.ParseCertificateRequest(csrDER)
	if err != nil {
		return nil, err
	}
	return csr, nil
}
Example #29
0
File: x509ez.go Project: polvi/cad
func CreateMinCertificateRequest() (*x509.CertificateRequest, *rsa.PrivateKey, error) {

	tmpl := &x509.CertificateRequest{}

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

	derBytes, err := x509.CreateCertificateRequest(rand.Reader, tmpl, priv)
	if err != nil {
		return nil, nil, err
	}
	csr, err := x509.ParseCertificateRequest(derBytes)
	if err != nil {
		return nil, nil, err
	}
	return csr, priv, nil
}
Example #30
0
// Creates a CSR. This is currently only meant for use when
// generating an intermediate certificate.
func createCSR(creationInfo *creationBundle) (*certutil.ParsedCSRBundle, error) {
	var err error
	result := &certutil.ParsedCSRBundle{}

	if err := certutil.GeneratePrivateKey(creationInfo.KeyType,
		creationInfo.KeyBits,
		result); err != nil {
		return nil, err
	}

	// Like many root CAs, other information is ignored
	subject := pkix.Name{
		CommonName: creationInfo.CommonName,
	}

	csrTemplate := &x509.CertificateRequest{
		Subject:        subject,
		DNSNames:       creationInfo.DNSNames,
		EmailAddresses: creationInfo.EmailAddresses,
		IPAddresses:    creationInfo.IPAddresses,
	}

	switch creationInfo.KeyType {
	case "rsa":
		csrTemplate.SignatureAlgorithm = x509.SHA256WithRSA
	case "ec":
		csrTemplate.SignatureAlgorithm = x509.ECDSAWithSHA256
	}

	csr, err := x509.CreateCertificateRequest(rand.Reader, csrTemplate, result.PrivateKey)
	if err != nil {
		return nil, errutil.InternalError{Err: fmt.Sprintf("unable to create certificate: %s", err)}
	}

	result.CSRBytes = csr
	result.CSR, err = x509.ParseCertificateRequest(csr)
	if err != nil {
		return nil, errutil.InternalError{Err: fmt.Sprintf("unable to parse created certificate: %s", err)}
	}

	return result, nil
}