Clash.Meta/common/net/tls.go

59 lines
1.4 KiB
Go
Raw Normal View History

2022-12-03 14:14:15 +08:00
package net
import (
"crypto/rand"
"crypto/rsa"
2022-12-03 14:14:15 +08:00
"crypto/tls"
"crypto/x509"
"encoding/pem"
2022-12-03 14:14:15 +08:00
"fmt"
"math/big"
2022-12-03 14:14:15 +08:00
)
2022-12-04 23:05:13 +08:00
type Path interface {
Resolve(path string) string
}
func ParseCert(certificate, privateKey string, path Path) (tls.Certificate, error) {
if certificate == "" && privateKey == "" {
return newRandomTLSKeyPair()
}
2022-12-03 14:14:15 +08:00
cert, painTextErr := tls.X509KeyPair([]byte(certificate), []byte(privateKey))
if painTextErr == nil {
return cert, nil
}
certificate = path.Resolve(certificate)
privateKey = path.Resolve(privateKey)
2022-12-03 14:14:15 +08:00
cert, loadErr := tls.LoadX509KeyPair(certificate, privateKey)
if loadErr != nil {
2022-12-04 23:05:13 +08:00
return tls.Certificate{}, fmt.Errorf("parse certificate failed, maybe format error:%s, or path error: %s", painTextErr.Error(), loadErr.Error())
2022-12-03 14:14:15 +08:00
}
return cert, nil
2022-12-04 23:05:13 +08:00
}
func newRandomTLSKeyPair() (tls.Certificate, error) {
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return tls.Certificate{}, err
}
template := x509.Certificate{SerialNumber: big.NewInt(1)}
certDER, err := x509.CreateCertificate(
rand.Reader,
&template,
&template,
&key.PublicKey,
key)
if err != nil {
return tls.Certificate{}, err
}
keyPEM := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)})
certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certDER})
tlsCert, err := tls.X509KeyPair(certPEM, keyPEM)
if err != nil {
return tls.Certificate{}, err
}
return tlsCert, nil
}