ref: d5669fb6eab6ee1b6741def4f86f43bf024f0713
client/pki.go
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
package main import ( "crypto/rand" "crypto/rsa" "crypto/x509" "crypto/x509/pkix" "encoding/pem" "fmt" "os" "path" ) func (c *YatsClient) CreateCsr(csrFile string) ([]byte, error) { //var oidEmailAddress = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 1} TlsKeyFile := path.Join(c.config.ClientCertDir, c.config.ClientCn+".key") TlsCertificate := path.Join(c.config.ClientCertDir, c.config.ClientCn+".crt") if fileExists(TlsKeyFile) { fmt.Printf("Private key file already exists: %v\n", TlsKeyFile) os.Exit(-1) } if fileExists(TlsCertificate) { fmt.Printf("Certificate file already exists: %v\n", TlsKeyFile) os.Exit(-1) } if ("" == c.config.ClientCn) || ("" == c.config.ClientOrganization) || ("" == c.config.ClientEmail) { fmt.Printf("Client name: [%v], organization: [%v], email address: [%v]\n", c.config.ClientCn, c.config.ClientOrganization, c.config.ClientEmail) fmt.Println("No param can be empty, exiting") os.Exit(-1) } keyBytes, _ := rsa.GenerateKey(rand.Reader, 1024) pemdata := pem.EncodeToMemory( &pem.Block{ Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(keyBytes), }, ) os.WriteFile(TlsKeyFile, pemdata, 0644) subj := pkix.Name{ CommonName: c.config.ClientCn, /* Country: []string{"AU"}, Province: []string{"Some-State"}, Locality: []string{"MyCity"}, */ Organization: []string{c.config.ClientOrganization}, //OrganizationalUnit: []string{organizationalUnit}, /* ExtraNames: []pkix.AttributeTypeAndValue{ { Type: oidEmailAddress, Value: asn1.RawValue{ Tag: asn1.TagIA5String, Bytes: []byte(c.config.ClientEmail), }, }, }, */ } template := x509.CertificateRequest{ Subject: subj, SignatureAlgorithm: x509.SHA256WithRSA, } csrBytes, _ := x509.CreateCertificateRequest(rand.Reader, &template, keyBytes) pemcsrdata := pem.EncodeToMemory( &pem.Block{ Type: "CERTIFICATE REQUEST", Bytes: csrBytes, }, ) os.WriteFile(csrFile, pemcsrdata, 0644) return pemcsrdata, nil } |