← history for client/pki.go
012f29ebclient/pki.go84 lines⬡ raw↓ download
 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
package client

import (
    "crypto/rand"
    "crypto/rsa"
    "crypto/x509"
    "crypto/x509/pkix"
    "encoding/pem"
    "fmt"
    "os"
    "path"
    "yats/internal/io"
)

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 io.FileExists(TlsKeyFile) {
        fmt.Printf("Private key file already exists: %v\n", TlsKeyFile)
        os.Exit(-1)
    }

    if io.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
}