Last active
October 15, 2022 09:25
-
-
Save geberl/40e79910b932d8ddccc41298a26e3304 to your computer and use it in GitHub Desktop.
Parse certificate *.pem files, because some new parsing errors got added in Go 1.15 and what previously may have been parsed ok might not now.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"crypto/x509" | |
"encoding/pem" | |
"fmt" | |
"io/ioutil" | |
"math" | |
"os" | |
"path/filepath" | |
) | |
func main() { | |
certDumpDir := "/Users/guenther/Development/backend/certs" | |
fileList := make([]string, 0) | |
err := filepath.Walk(certDumpDir, func(path string, f os.FileInfo, err error) error { | |
fileList = append(fileList, path) | |
return err | |
}) | |
if err != nil { | |
fmt.Printf("unable to build file list: %v", err) | |
} | |
for _, filePath := range fileList { | |
fileNameNew, err := generateFilename(filePath) | |
if err != nil { | |
fmt.Printf("invalid cert: %s\n", filePath) | |
} else { | |
fmt.Printf("valid cert: %s\n", fileNameNew) | |
} | |
} | |
} | |
func generateFilename(path string) (string, error) { | |
content, err := ioutil.ReadFile(path) | |
if err != nil { | |
return "", fmt.Errorf("unable to read file content: %v", err) | |
} | |
expiryEpoch, err := getExpiryEpoch(content) | |
if err != nil { | |
return "", fmt.Errorf("invalid cert: %v", err) | |
} | |
fixedLengthInverseExpiryEpoch := fmt.Sprintf("%016x", math.MaxInt64-expiryEpoch) | |
filePath := fmt.Sprintf("%s_%s.pem", fixedLengthInverseExpiryEpoch, "rest") | |
return filePath, nil | |
} | |
func getExpiryEpoch(pemData []byte) (int64, error) { | |
// Only the first block (= end-entity certificate) is interesting here, the rest of the chain doesn't matter. | |
block, _ := pem.Decode(pemData) | |
if block == nil { | |
return 0, fmt.Errorf("invalid PEM-encoded certificate") | |
} | |
if block.Type != "CERTIFICATE" { | |
return 0, fmt.Errorf("invalid PEM block type: %s", block.Type) | |
} | |
cert, err := x509.ParseCertificate(block.Bytes) | |
if err != nil { | |
return 0, err | |
} | |
return cert.NotAfter.Unix(), nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment