github.com/lastbackend/toolkit@v0.0.0-20241020043710-cafa37b95aad/pkg/util/tls/tls.go (about) 1 /* 2 Copyright [2014] - [2023] The Last.Backend authors. 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 tls 18 19 import ( 20 "bytes" 21 "crypto/ecdsa" 22 "crypto/elliptic" 23 "crypto/rand" 24 "crypto/tls" 25 "crypto/x509" 26 "crypto/x509/pkix" 27 "encoding/pem" 28 "math/big" 29 "net" 30 "time" 31 ) 32 33 func Certificate(host ...string) (tls.Certificate, error) { 34 priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) 35 if err != nil { 36 return tls.Certificate{}, err 37 } 38 39 notBefore := time.Now() 40 notAfter := notBefore.Add(time.Hour * 24 * 365) 41 42 serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) 43 serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) 44 if err != nil { 45 return tls.Certificate{}, err 46 } 47 48 template := x509.Certificate{ 49 SerialNumber: serialNumber, 50 Subject: pkix.Name{ 51 Organization: []string{"Acme Co"}, 52 }, 53 NotBefore: notBefore, 54 NotAfter: notAfter, 55 56 KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature, 57 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, 58 BasicConstraintsValid: true, 59 } 60 61 for _, h := range host { 62 if ip := net.ParseIP(h); ip != nil { 63 template.IPAddresses = append(template.IPAddresses, ip) 64 } else { 65 template.DNSNames = append(template.DNSNames, h) 66 } 67 } 68 69 template.IsCA = true 70 template.KeyUsage |= x509.KeyUsageCertSign 71 72 derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv) 73 if err != nil { 74 return tls.Certificate{}, err 75 } 76 77 // create public key 78 certOut := bytes.NewBuffer(nil) 79 80 err = pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}) 81 if err != nil { 82 return tls.Certificate{}, err 83 } 84 85 // create private key 86 keyOut := bytes.NewBuffer(nil) 87 b, err := x509.MarshalECPrivateKey(priv) 88 if err != nil { 89 return tls.Certificate{}, err 90 } 91 err = pem.Encode(keyOut, &pem.Block{Type: "EC PRIVATE KEY", Bytes: b}) 92 if err != nil { 93 return tls.Certificate{}, err 94 } 95 96 return tls.X509KeyPair(certOut.Bytes(), keyOut.Bytes()) 97 }