github.com/bartle-stripe/trillian@v1.2.1/testonly/setup/tls.go (about) 1 // Copyright 2018 Google Inc. All Rights Reserved. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package setup 16 17 import ( 18 "crypto/rand" 19 "crypto/rsa" 20 "crypto/tls" 21 "crypto/x509" 22 "encoding/pem" 23 "math/big" 24 "testing" 25 "time" 26 ) 27 28 // NewTLSCertificate returns a random TLS Certificate for testing. 29 func NewTLSCertificate(t *testing.T) tls.Certificate { 30 t.Helper() 31 32 priv, err := rsa.GenerateKey(rand.Reader, 2048) 33 if err != nil { 34 t.Errorf("failed to generate RSA key: %s", err) 35 } 36 37 privBytes := x509.MarshalPKCS1PrivateKey(priv) 38 key := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: privBytes}) 39 40 // Generate public certificate. 41 serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) 42 serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) 43 if err != nil { 44 t.Errorf("failed to generate serial number: %s", err) 45 } 46 47 template := x509.Certificate{ 48 SerialNumber: serialNumber, 49 NotBefore: time.Time{}, 50 NotAfter: time.Now().Add(time.Hour), 51 DNSNames: []string{"localhost"}, 52 } 53 pubBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv) 54 if err != nil { 55 t.Errorf("failed to generate TLS public certificate: %s", err) 56 } 57 58 crt := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: pubBytes}) 59 60 c, err := tls.X509KeyPair(crt, key) 61 if err != nil { 62 t.Errorf("failed to parse the public/private key pair: %s", err) 63 } 64 65 return c 66 }