ref: 0102aa21efe7d4d94a56fc48566c89232fb68064
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 84 85 86 87 88 89 90 |
package main import ( "crypto/rand" "crypto/rsa" "crypto/x509" "crypto/x509/pkix" "encoding/asn1" "encoding/pem" "fmt" "os" ) func fileExists(fileName string) bool { _, error := os.Stat(fileName) if os.IsNotExist(error) { return false } return true } func (c *YatsClient) CreateCsr() ([]byte, error) { var oidEmailAddress = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 1} if fileExists(c.config.TlsKeyFile) { fmt.Printf("Private key file already exists: %v\n", c.config.TlsKeyFile) os.Exit(-1) } if fileExists(c.config.TlsCertificate) { fmt.Printf("Certificate file already exists: %v\n", c.config.TlsKeyFile) os.Exit(-1) } if ("" == c.config.ClientCnName) || ("" == c.config.ClientOrganization) || ("" == c.config.ClientCnName) { fmt.Printf("Client name: [%v], organization: [%v], email address: [%v]\n", c.config.ClientCnName, c.config.ClientOrganization, c.config.ClientCnName) 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(c.config.TlsKeyFile, pemdata, 0644) subj := pkix.Name{ CommonName: c.config.ClientCnName, /* 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.ClientCnName), }, }, }, } template := x509.CertificateRequest{ Subject: subj, SignatureAlgorithm: x509.SHA256WithRSA, } csrBytes, _ := x509.CreateCertificateRequest(rand.Reader, &template, keyBytes) pem.Encode(os.Stdout, &pem.Block{Type: "CERTIFICATE REQUEST", Bytes: csrBytes}) pemcsrdata := pem.EncodeToMemory( &pem.Block{ Type: "CERTIFICATE REQUEST", Bytes: csrBytes, }, ) os.WriteFile("csr.pem", pemcsrdata, 0644) return pemcsrdata, nil } |