cert_test.go 2.1 KB

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