github.com/mook-as/cf-cli@v7.0.0-beta.28.0.20200120190804-b91c115fae48+incompatible/cf/util/testhelpers/net/make_tls_cert.go (about) 1 package net 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 MakeSelfSignedTLSCert() tls.Certificate { 17 return generateCert([]string{"127.0.0.1", "::1"}, time.Date(2020, time.December, 1, 0, 0, 0, 0, time.UTC), true) 18 } 19 20 func MakeTLSCertWithInvalidHost() tls.Certificate { 21 return generateCert([]string{"example.com"}, time.Date(2020, time.December, 1, 0, 0, 0, 0, time.UTC), true) 22 } 23 24 func MakeExpiredTLSCert() tls.Certificate { 25 return generateCert([]string{"127.0.0.1", "::1"}, time.Date(2000, time.December, 1, 0, 0, 0, 0, time.UTC), true) 26 } 27 28 func MakeUnauthorizedTLSCert() tls.Certificate { 29 return generateCert([]string{"127.0.0.1", "::1"}, time.Date(2020, time.December, 1, 0, 0, 0, 0, time.UTC), false) 30 } 31 32 func generateCert(hosts []string, notAfter time.Time, isAuthorizedToSign bool) tls.Certificate { 33 priv, err := rsa.GenerateKey(rand.Reader, 1024) 34 if err != nil { 35 panic(err) 36 } 37 38 template := x509.Certificate{ 39 SerialNumber: new(big.Int).SetInt64(0), 40 Subject: pkix.Name{ 41 Organization: []string{"Acme Co"}, 42 }, 43 NotBefore: time.Date(1980, time.January, 1, 0, 0, 0, 0, time.UTC), 44 NotAfter: notAfter, 45 46 KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature, 47 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, 48 BasicConstraintsValid: true, 49 } 50 51 for _, host := range hosts { 52 if ip := net.ParseIP(host); ip != nil { 53 template.IPAddresses = append(template.IPAddresses, ip) 54 } else { 55 template.DNSNames = append(template.DNSNames, host) 56 } 57 } 58 59 if isAuthorizedToSign { 60 template.IsCA = true 61 template.KeyUsage |= x509.KeyUsageCertSign 62 } 63 64 derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv) 65 if err != nil { 66 panic(err) 67 } 68 69 certOut := new(bytes.Buffer) 70 pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}) 71 72 keyOut := new(bytes.Buffer) 73 pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)}) 74 75 cert, err := tls.X509KeyPair(certOut.Bytes(), keyOut.Bytes()) 76 if err != nil { 77 panic(err) 78 } 79 80 return cert 81 }