|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "crypto/rand" |
| 6 | + "crypto/rsa" |
| 7 | + "crypto/tls" |
| 8 | + "crypto/x509" |
| 9 | + "crypto/x509/pkix" |
| 10 | + "encoding/pem" |
| 11 | + "math/big" |
| 12 | + "net" |
| 13 | + "time" |
| 14 | +) |
| 15 | + |
| 16 | +func GenerateCertificate() (tls.Certificate, error) { |
| 17 | + max := new(big.Int).Lsh(big.NewInt(1), 128) |
| 18 | + serialNumber, _ := rand.Int(rand.Reader, max) |
| 19 | + subject := pkix.Name{ |
| 20 | + Organization: []string{"TcpProxy App co."}, |
| 21 | + OrganizationalUnit: []string{"TcpProxy App"}, |
| 22 | + CommonName: "TcpProxy App", |
| 23 | + } |
| 24 | + |
| 25 | + ipAddress := make([]net.IP, 0) |
| 26 | + ipAddress = append(ipAddress, net.ParseIP("127.0.0.1")) |
| 27 | + |
| 28 | + template := x509.Certificate{ |
| 29 | + SerialNumber: serialNumber, |
| 30 | + Subject: subject, |
| 31 | + NotBefore: time.Now(), |
| 32 | + NotAfter: time.Now().Add(365 * 24 * time.Hour), |
| 33 | + KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature, |
| 34 | + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, |
| 35 | + IPAddresses: ipAddress, |
| 36 | + } |
| 37 | + pk, _ := rsa.GenerateKey(rand.Reader, 4096) |
| 38 | + |
| 39 | + derBytes, _ := x509.CreateCertificate(rand.Reader, &template, &template, &pk.PublicKey, pk) |
| 40 | + |
| 41 | + certOut := bytes.NewBuffer(make([]byte, 0)) |
| 42 | + pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}) |
| 43 | + |
| 44 | + keyOut := bytes.NewBuffer(make([]byte, 0)) |
| 45 | + pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(pk)}) |
| 46 | + |
| 47 | + return tls.X509KeyPair(certOut.Bytes(), keyOut.Bytes()) |
| 48 | +} |
| 49 | + |
| 50 | +func TlsConfigClient(servername string) (*tls.Config, error) { |
| 51 | + var certs tls.Certificate |
| 52 | + var err error |
| 53 | + |
| 54 | + certs, err = GenerateCertificate() |
| 55 | + if err != nil { |
| 56 | + return nil, err |
| 57 | + } |
| 58 | + |
| 59 | + return &tls.Config{ |
| 60 | + MinVersion: tls.VersionTLS12, |
| 61 | + MaxVersion: tls.VersionTLS13, |
| 62 | + ServerName: servername, |
| 63 | + InsecureSkipVerify: true, |
| 64 | + Certificates: []tls.Certificate{certs}, |
| 65 | + }, nil |
| 66 | +} |
| 67 | + |
| 68 | +func TlsConfigServer() (*tls.Config, error) { |
| 69 | + var certs tls.Certificate |
| 70 | + var err error |
| 71 | + |
| 72 | + certs, err = GenerateCertificate() |
| 73 | + if err != nil { |
| 74 | + return nil, err |
| 75 | + } |
| 76 | + |
| 77 | + return &tls.Config{ |
| 78 | + MinVersion: tls.VersionTLS12, |
| 79 | + MaxVersion: tls.VersionTLS13, |
| 80 | + Certificates: []tls.Certificate{certs}, |
| 81 | + ClientAuth: tls.RequestClientCert, |
| 82 | + }, nil |
| 83 | +} |
0 commit comments