Skip to content

Commit

Permalink
feat: temp cert and key file creation
Browse files Browse the repository at this point in the history
  • Loading branch information
shoriwe committed Jun 3, 2023
1 parent 43034fc commit 07c5251
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
30 changes: 30 additions & 0 deletions utils/crypto/tls.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"crypto/tls"
"crypto/x509"
"encoding/pem"
"io/ioutil"
"math/big"
"time"
)
Expand Down Expand Up @@ -38,3 +39,32 @@ func DefaultTLSConfig() *tls.Config {
InsecureSkipVerify: true,
}
}

func TempCertKey() (string, string) {
privateKey, _ := rsa.GenerateKey(rand.Reader, 2048)
sN, _ := rand.Int(rand.Reader, big.NewInt(0xFF_FF_FF_FF_FF_FF_FF))
template := &x509.Certificate{
SerialNumber: sN,
NotBefore: time.Now(),
NotAfter: time.Now().AddDate(120, 0, 0),
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
}
certDER, _ := x509.CreateCertificate(rand.Reader, template, template, &privateKey.PublicKey, privateKey)
privateKeyPEM := &pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(privateKey),
}
certPEM := &pem.Block{
Type: "CERTIFICATE",
Bytes: certDER,
}
privateKeyFile, _ := ioutil.TempFile("", "privatekey*.pem")
defer privateKeyFile.Close()
pem.Encode(privateKeyFile, privateKeyPEM)
certFile, _ := ioutil.TempFile("", "certificate*.pem")
defer certFile.Close()
pem.Encode(certFile, certPEM)
return certFile.Name(), privateKeyFile.Name()
}
11 changes: 11 additions & 0 deletions utils/crypto/tls_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package crypto

import (
"crypto/tls"
"os"
"testing"

"github.com/shoriwe/fullproxy/v3/utils/network"
Expand Down Expand Up @@ -33,3 +34,13 @@ func TestDefaultTLSConfig(t *testing.T) {
signal <- struct{}{}
})
}

func TestTempCertKey(t *testing.T) {
t.Run("Valid", func(tt *testing.T) {
cert, key := TempCertKey()
defer os.Remove(cert)
defer os.Remove(key)
_, err := tls.LoadX509KeyPair(cert, key)
assert.Nil(tt, err)
})
}

0 comments on commit 07c5251

Please sign in to comment.