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
| func GenK8sUser(cn,o string) { caCert,caPriKey:= parseK8sCA(CAFILE,CAKEY) if cn == "" { goft.Error(fmt.Errorf("CN is required")) }
certTemplate := &x509.Certificate{ SerialNumber: big.NewInt(rd.Int63()), Subject: pkix.Name{ Country: []string{"CN"}, Organization: []string{o}, Province: []string{"beijing"}, CommonName: cn, Locality: []string{"beijing"}, }, NotBefore: time.Now(), NotAfter: time.Now().AddDate(1, 0, 0), BasicConstraintsValid: true, IsCA: false, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth}, KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageDataEncipherment, EmailAddresses: []string{"UserAccount@example.com"}, }
priKey, err := rsa.GenerateKey(rand.Reader, 2048) if err != nil { return } clientCert, err := x509.CreateCertificate(rand.Reader, certTemplate, caCert, &priKey.PublicKey, caPriKey) if err != nil { return }
clientCertPem := &pem.Block{ Type: "CERTIFICATE", Bytes: clientCert, }
certName:= fmt.Sprintf("./k8susers/%s.pem",cn)
clientCertFile, err := os.OpenFile(certName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) if err != nil { log.Fatal(err) } err = pem.Encode(clientCertFile, clientCertPem) if err != nil { log.Fatal(err) }
buf := x509.MarshalPKCS1PrivateKey(priKey) keyPem := &pem.Block{ Type: "PRIVATE KEY", Bytes: buf, }
certKeyName:= fmt.Sprintf("./k8susers/%s_key.pem",cn) clientKeyFile, _ := os.OpenFile(certKeyName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
err = pem.Encode(clientKeyFile, keyPem) if err != nil { log.Fatal(err) }
}
|