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