github.com/turbot/steampipe@v1.7.0-rc.0.0.20240517123944-7cef272d4458/pkg/db/sslio/sslio.go (about)

     1  package sslio
     2  
     3  import (
     4  	"bytes"
     5  	"crypto/rsa"
     6  	"crypto/x509"
     7  	"encoding/pem"
     8  	"fmt"
     9  	"log"
    10  	"os"
    11  
    12  	"github.com/turbot/steampipe/pkg/utils"
    13  )
    14  
    15  func ParseCertificateInLocation(location string) (*x509.Certificate, error) {
    16  	utils.LogTime("db_local.parseCertificateInLocation start")
    17  	defer utils.LogTime("db_local.parseCertificateInLocation end")
    18  
    19  	rootCertRaw, err := os.ReadFile(location)
    20  	if err != nil {
    21  		// if we can't read the certificate, then there's a problem with permissions
    22  		return nil, err
    23  	}
    24  	// decode the pem blocks
    25  	rootPemBlock, _ := pem.Decode(rootCertRaw)
    26  	if rootPemBlock == nil {
    27  		return nil, fmt.Errorf("could not decode PEM blocks from certificate at %s", location)
    28  	}
    29  	// parse the PEM Blocks to Certificates
    30  	return x509.ParseCertificate(rootPemBlock.Bytes)
    31  }
    32  
    33  func WriteCertificate(path string, certificate []byte) error {
    34  	return writeAsPEM(path, "CERTIFICATE", certificate)
    35  }
    36  
    37  func WritePrivateKey(path string, key *rsa.PrivateKey) error {
    38  	return writeAsPEM(path, "RSA PRIVATE KEY", x509.MarshalPKCS1PrivateKey(key))
    39  }
    40  
    41  func writeAsPEM(location string, pemType string, b []byte) error {
    42  	pemData := new(bytes.Buffer)
    43  	err := pem.Encode(pemData, &pem.Block{
    44  		Type:  pemType,
    45  		Bytes: b,
    46  	})
    47  	if err != nil {
    48  		log.Println("[INFO] Failed to encode to PEM")
    49  		return err
    50  	}
    51  	if err := os.WriteFile(location, pemData.Bytes(), 0600); err != nil {
    52  		log.Println("[INFO] Failed to save pem at", location)
    53  		return err
    54  	}
    55  	return nil
    56  }