github.com/xmplusdev/xmcore@v1.8.11-0.20240412132628-5518b55526af/common/protocol/tls/cert/cert_test.go (about) 1 package cert 2 3 import ( 4 "context" 5 "crypto/x509" 6 "encoding/json" 7 "os" 8 "strings" 9 "testing" 10 "time" 11 12 "github.com/xmplusdev/xmcore/common" 13 "github.com/xmplusdev/xmcore/common/task" 14 ) 15 16 func TestGenerate(t *testing.T) { 17 err := generate(nil, true, true, "ca") 18 if err != nil { 19 t.Fatal(err) 20 } 21 } 22 23 func generate(domainNames []string, isCA bool, jsonOutput bool, fileOutput string) error { 24 commonName := "Xray Root CA" 25 organization := "Xray Inc" 26 27 expire := time.Hour * 3 28 29 var opts []Option 30 if isCA { 31 opts = append(opts, Authority(isCA)) 32 opts = append(opts, KeyUsage(x509.KeyUsageCertSign|x509.KeyUsageKeyEncipherment|x509.KeyUsageDigitalSignature)) 33 } 34 35 opts = append(opts, NotAfter(time.Now().Add(expire))) 36 opts = append(opts, CommonName(commonName)) 37 if len(domainNames) > 0 { 38 opts = append(opts, DNSNames(domainNames...)) 39 } 40 opts = append(opts, Organization(organization)) 41 42 cert, err := Generate(nil, opts...) 43 if err != nil { 44 return newError("failed to generate TLS certificate").Base(err) 45 } 46 47 if jsonOutput { 48 printJSON(cert) 49 } 50 51 if len(fileOutput) > 0 { 52 if err := printFile(cert, fileOutput); err != nil { 53 return err 54 } 55 } 56 57 return nil 58 } 59 60 type jsonCert struct { 61 Certificate []string `json:"certificate"` 62 Key []string `json:"key"` 63 } 64 65 func printJSON(certificate *Certificate) { 66 certPEM, keyPEM := certificate.ToPEM() 67 jCert := &jsonCert{ 68 Certificate: strings.Split(strings.TrimSpace(string(certPEM)), "\n"), 69 Key: strings.Split(strings.TrimSpace(string(keyPEM)), "\n"), 70 } 71 content, err := json.MarshalIndent(jCert, "", " ") 72 common.Must(err) 73 os.Stdout.Write(content) 74 os.Stdout.WriteString("\n") 75 } 76 77 func printFile(certificate *Certificate, name string) error { 78 certPEM, keyPEM := certificate.ToPEM() 79 return task.Run(context.Background(), func() error { 80 return writeFile(certPEM, name+"_cert.pem") 81 }, func() error { 82 return writeFile(keyPEM, name+"_key.pem") 83 }) 84 } 85 86 func writeFile(content []byte, name string) error { 87 f, err := os.Create(name) 88 if err != nil { 89 return err 90 } 91 defer f.Close() 92 93 return common.Error2(f.Write(content)) 94 }