cert_test.go 2.0 KB

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