istio.io/istio@v0.0.0-20240520182934-d79c90f27776/tests/integration/pilot/forwardproxy/cert_gen.go (about) 1 //go:build integ 2 // +build integ 3 4 // Copyright Istio Authors 5 // 6 // Licensed under the Apache License, Version 2.0 (the "License"); 7 // you may not use this file except in compliance with the License. 8 // You may obtain a copy of the License at 9 // 10 // http://www.apache.org/licenses/LICENSE-2.0 11 // 12 // Unless required by applicable law or agreed to in writing, software 13 // distributed under the License is distributed on an "AS IS" BASIS, 14 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 // See the License for the specific language governing permissions and 16 // limitations under the License. 17 18 package forwardproxy 19 20 import ( 21 "fmt" 22 "os" 23 "os/exec" 24 "path/filepath" 25 ) 26 27 func GenerateKeyAndCertificate(subject, dir string) (string, string, error) { 28 keyFile := filepath.Join(dir, fmt.Sprintf("%s-key.pem", subject)) 29 crtFile := filepath.Join(dir, fmt.Sprintf("%s-cert.pem", subject)) 30 if err := openssl( 31 "req", "-x509", "-sha256", "-nodes", 32 "-days", "365", "-newkey", "rsa:2048", 33 "-subj", fmt.Sprintf("/CN=%s", subject), 34 "-keyout", keyFile, 35 "-out", crtFile, 36 ); err != nil { 37 return "", "", fmt.Errorf("failed to generate private key and certificate: %s", err) 38 } 39 key, err := os.ReadFile(keyFile) 40 if err != nil { 41 return "", "", fmt.Errorf("failed to read private key from file %s: %s", keyFile, err) 42 } 43 crt, err := os.ReadFile(crtFile) 44 if err != nil { 45 return "", "", fmt.Errorf("failed to read certificate from file %s: %s", crtFile, err) 46 } 47 return string(key), string(crt), nil 48 } 49 50 func openssl(args ...string) error { 51 cmd := exec.Command("openssl", args...) 52 if out, err := cmd.CombinedOutput(); err != nil { 53 return fmt.Errorf("command %s failed: %q %v", cmd.String(), string(out), err) 54 } 55 return nil 56 }