package pki import ( "crypto/rsa" "crypto/x509" "encoding/pem" "fmt" "os" ) // ParseCSRFromBytes parses a PEM-encoded CSR from bytes func ParseCSRFromBytes(csrData []byte) (*x509.CertificateRequest, error) { block, _ := pem.Decode(csrData) if block == nil || block.Type != "CERTIFICATE REQUEST" { return nil, fmt.Errorf("failed to decode PEM block containing CSR") } csr, err := x509.ParseCertificateRequest(block.Bytes) if err != nil { return nil, fmt.Errorf("failed to parse CSR: %w", err) } return csr, nil } // LoadCertificate loads an X.509 certificate from a file func LoadCertificate(certPath string) (*x509.Certificate, error) { certPEM, err := os.ReadFile(certPath) if err != nil { return nil, fmt.Errorf("failed to read certificate file: %w", err) } block, _ := pem.Decode(certPEM) if block == nil || block.Type != "CERTIFICATE" { return nil, fmt.Errorf("failed to decode PEM block containing certificate") } cert, err := x509.ParseCertificate(block.Bytes) if err != nil { return nil, fmt.Errorf("failed to parse certificate: %w", err) } return cert, nil } // LoadPrivateKey loads an RSA private key from a file func LoadPrivateKey(keyPath string) (*rsa.PrivateKey, error) { keyPEM, err := os.ReadFile(keyPath) if err != nil { return nil, fmt.Errorf("failed to read key file: %w", err) } block, _ := pem.Decode(keyPEM) if block == nil || block.Type != "RSA PRIVATE KEY" { return nil, fmt.Errorf("failed to decode PEM block containing private key") } key, err := x509.ParsePKCS1PrivateKey(block.Bytes) if err != nil { return nil, fmt.Errorf("failed to parse private key: %w", err) } return key, nil }