cert.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. package cert
  2. import (
  3. "crypto/ecdsa"
  4. "crypto/ed25519"
  5. "crypto/elliptic"
  6. "crypto/rand"
  7. "crypto/rsa"
  8. "crypto/x509"
  9. "encoding/asn1"
  10. "encoding/pem"
  11. "math/big"
  12. "time"
  13. "github.com/xtls/xray-core/common"
  14. "github.com/xtls/xray-core/common/errors"
  15. )
  16. type Certificate struct {
  17. // certificate in ASN.1 DER format
  18. Certificate []byte
  19. // Private key in ASN.1 DER format
  20. PrivateKey []byte
  21. }
  22. func ParseCertificate(certPEM []byte, keyPEM []byte) (*Certificate, error) {
  23. certBlock, _ := pem.Decode(certPEM)
  24. if certBlock == nil {
  25. return nil, errors.New("failed to decode certificate")
  26. }
  27. keyBlock, _ := pem.Decode(keyPEM)
  28. if keyBlock == nil {
  29. return nil, errors.New("failed to decode key")
  30. }
  31. return &Certificate{
  32. Certificate: certBlock.Bytes,
  33. PrivateKey: keyBlock.Bytes,
  34. }, nil
  35. }
  36. func (c *Certificate) ToPEM() ([]byte, []byte) {
  37. return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: c.Certificate}),
  38. pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: c.PrivateKey})
  39. }
  40. type Option func(*x509.Certificate)
  41. func Authority(isCA bool) Option {
  42. return func(cert *x509.Certificate) {
  43. cert.IsCA = isCA
  44. }
  45. }
  46. func NotBefore(t time.Time) Option {
  47. return func(c *x509.Certificate) {
  48. c.NotBefore = t
  49. }
  50. }
  51. func NotAfter(t time.Time) Option {
  52. return func(c *x509.Certificate) {
  53. c.NotAfter = t
  54. }
  55. }
  56. func DNSNames(names ...string) Option {
  57. return func(c *x509.Certificate) {
  58. c.DNSNames = names
  59. }
  60. }
  61. func CommonName(name string) Option {
  62. return func(c *x509.Certificate) {
  63. c.Subject.CommonName = name
  64. }
  65. }
  66. func KeyUsage(usage x509.KeyUsage) Option {
  67. return func(c *x509.Certificate) {
  68. c.KeyUsage = usage
  69. }
  70. }
  71. func Organization(org string) Option {
  72. return func(c *x509.Certificate) {
  73. c.Subject.Organization = []string{org}
  74. }
  75. }
  76. func MustGenerate(parent *Certificate, opts ...Option) *Certificate {
  77. cert, err := Generate(parent, opts...)
  78. common.Must(err)
  79. return cert
  80. }
  81. func publicKey(priv interface{}) interface{} {
  82. switch k := priv.(type) {
  83. case *rsa.PrivateKey:
  84. return &k.PublicKey
  85. case *ecdsa.PrivateKey:
  86. return &k.PublicKey
  87. case ed25519.PrivateKey:
  88. return k.Public().(ed25519.PublicKey)
  89. default:
  90. return nil
  91. }
  92. }
  93. func Generate(parent *Certificate, opts ...Option) (*Certificate, error) {
  94. var (
  95. pKey interface{}
  96. parentKey interface{}
  97. err error
  98. )
  99. // higher signing performance than RSA2048
  100. selfKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  101. if err != nil {
  102. return nil, errors.New("failed to generate self private key").Base(err)
  103. }
  104. parentKey = selfKey
  105. if parent != nil {
  106. if _, e := asn1.Unmarshal(parent.PrivateKey, &ecPrivateKey{}); e == nil {
  107. pKey, err = x509.ParseECPrivateKey(parent.PrivateKey)
  108. } else if _, e := asn1.Unmarshal(parent.PrivateKey, &pkcs8{}); e == nil {
  109. pKey, err = x509.ParsePKCS8PrivateKey(parent.PrivateKey)
  110. } else if _, e := asn1.Unmarshal(parent.PrivateKey, &pkcs1PrivateKey{}); e == nil {
  111. pKey, err = x509.ParsePKCS1PrivateKey(parent.PrivateKey)
  112. }
  113. if err != nil {
  114. return nil, errors.New("failed to parse parent private key").Base(err)
  115. }
  116. parentKey = pKey
  117. }
  118. serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
  119. serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
  120. if err != nil {
  121. return nil, errors.New("failed to generate serial number").Base(err)
  122. }
  123. template := &x509.Certificate{
  124. SerialNumber: serialNumber,
  125. NotBefore: time.Now().Add(time.Hour * -1),
  126. NotAfter: time.Now().Add(time.Hour),
  127. KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
  128. ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
  129. BasicConstraintsValid: true,
  130. }
  131. parentCert := template
  132. if parent != nil {
  133. pCert, err := x509.ParseCertificate(parent.Certificate)
  134. if err != nil {
  135. return nil, errors.New("failed to parse parent certificate").Base(err)
  136. }
  137. parentCert = pCert
  138. }
  139. if parentCert.NotAfter.Before(template.NotAfter) {
  140. template.NotAfter = parentCert.NotAfter
  141. }
  142. if parentCert.NotBefore.After(template.NotBefore) {
  143. template.NotBefore = parentCert.NotBefore
  144. }
  145. for _, opt := range opts {
  146. opt(template)
  147. }
  148. derBytes, err := x509.CreateCertificate(rand.Reader, template, parentCert, publicKey(selfKey), parentKey)
  149. if err != nil {
  150. return nil, errors.New("failed to create certificate").Base(err)
  151. }
  152. privateKey, err := x509.MarshalPKCS8PrivateKey(selfKey)
  153. if err != nil {
  154. return nil, errors.New("Unable to marshal private key").Base(err)
  155. }
  156. return &Certificate{
  157. Certificate: derBytes,
  158. PrivateKey: privateKey,
  159. }, nil
  160. }