github.com/mirantis/virtlet@v1.5.2-0.20191204181327-1659b8a48e9b/pkg/utils/testing/https.go (about) 1 /* 2 Copyright 2018 Mirantis 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package testing 18 19 import ( 20 "bytes" 21 "crypto/rand" 22 "crypto/rsa" 23 "crypto/x509" 24 "encoding/pem" 25 "math/big" 26 "net" 27 "testing" 28 "time" 29 ) 30 31 func GenerateCert(t *testing.T, isCA bool, host string, signer *x509.Certificate, key *rsa.PrivateKey) (*x509.Certificate, *rsa.PrivateKey) { 32 serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 64) 33 serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) 34 if err != nil { 35 t.Fatal(err) 36 } 37 if key == nil { 38 key, err = rsa.GenerateKey(rand.Reader, 2048) 39 if err != nil { 40 t.Fatal(err) 41 } 42 } 43 44 template := &x509.Certificate{ 45 SerialNumber: serialNumber, 46 NotBefore: time.Now(), 47 NotAfter: time.Now().Add(24 * time.Hour), 48 KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature, 49 BasicConstraintsValid: true, 50 } 51 52 if ip := net.ParseIP(host); ip != nil { 53 template.IPAddresses = []net.IP{ip} 54 } else { 55 template.DNSNames = []string{host} 56 } 57 58 if isCA { 59 template.IsCA = true 60 template.KeyUsage |= x509.KeyUsageCertSign 61 } 62 63 if signer == nil { 64 signer = template 65 } 66 67 der, err := x509.CreateCertificate(rand.Reader, template, signer, &key.PublicKey, key) 68 if err != nil { 69 t.Fatal(err) 70 } 71 cert, err := x509.ParseCertificate(der) 72 if err != nil { 73 t.Fatal(err) 74 } 75 return cert, key 76 } 77 78 func EncodePEMCert(cert *x509.Certificate) string { 79 buf := bytes.NewBufferString("") 80 pem.Encode(buf, &pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw}) 81 return buf.String() 82 } 83 84 func EncodePEMKey(key *rsa.PrivateKey) string { 85 buf := bytes.NewBufferString("") 86 pem.Encode(buf, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)}) 87 return buf.String() 88 }