Author: Paolo Lulli <paolo@lulli.net>
Add CSR generation in GO
golang/csr/csr.go | 58 +++++++++++++++++++++++++++++++++++++++++++++++++
diff --git a/golang/csr/csr.go b/golang/csr/csr.go new file mode 100644 index 0000000000000000000000000000000000000000..a2ae2b38a1e8cf22ba23660d578d70e847084508 --- /dev/null +++ b/golang/csr/csr.go @@ -0,0 +1,58 @@ +package main + +import ( + "crypto/rand" + "crypto/rsa" + "crypto/x509" + "crypto/x509/pkix" + "encoding/asn1" + "encoding/pem" + "fmt" + "os" +) + +var oidEmailAddress = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 1} + +func main() { + printCsr("email@example.com", "example.com") +} + +//func Write(output *os.File) { output.Write } + +func printCsr(emailAddress string, commonName string) { + keyBytes, _ := rsa.GenerateKey(rand.Reader, 1024) + + //emailAddress := "test@example.com" + subj := pkix.Name{ + CommonName: commonName, + Country: []string{"AU"}, + /* + Province: []string{"Some-State"}, + Locality: []string{"MyCity"}, + Organization: []string{"Company Ltd"}, + OrganizationalUnit: []string{"IT"}, + */ + } + rawSubj := subj.ToRDNSequence() + rawSubj = append(rawSubj, []pkix.AttributeTypeAndValue{ + {Type: oidEmailAddress, Value: emailAddress}, + }) + + asn1Subj, _ := asn1.Marshal(rawSubj) + template := x509.CertificateRequest{ + RawSubject: asn1Subj, + EmailAddresses: []string{emailAddress}, + SignatureAlgorithm: x509.SHA256WithRSA, + } + + csrBytes, _ := x509.CreateCertificateRequest(rand.Reader, &template, keyBytes) + + //pem.Encode(os.Stdout, &pem.Block{Type: "CERTIFICATE REQUEST", Bytes: csrBytes}) + var f, err = os.Create(emailAddress + ".csr") + if nil != err { + fmt.Print("Failed to create file") + } + + pem.Encode(f, &pem.Block{Type: "CERTIFICATE REQUEST", Bytes: csrBytes}) + +}