Last active
March 14, 2025 09:32
-
-
Save kingster/aac19ce914f4f2834238fdfd4e8bbc9b to your computer and use it in GitHub Desktop.
Convert PEM String to tls.Certificate
This file contains hidden or 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
// Convert PEM string to tls.Certificate | |
// Based on https://medium.com/@prateeknischal25/using-encrypted-private-keys-with-golang-server-379919955854 | |
func X509Pem(b []byte) (tls.Certificate, error) { | |
var pemBlocks []*pem.Block | |
var v *pem.Block | |
var pkey []byte | |
for { | |
v, b = pem.Decode(b) | |
if v == nil { | |
break | |
} | |
if v.Type == "RSA PRIVATE KEY" || v.Type == "PRIVATE KEY" { | |
pkey = pem.EncodeToMemory(v) | |
} else { | |
pemBlocks = append(pemBlocks, v) | |
} | |
} | |
if len(pemBlocks) == 0 { | |
return tls.Certificate{}, fmt.Errorf("no certificate found") | |
} | |
// Combine all certificate blocks into a single PEM-encoded byte slice | |
var certPEM []byte | |
for _, block := range pemBlocks { | |
certPEM = append(certPEM, pem.EncodeToMemory(block)...) | |
} | |
return tls.X509KeyPair(certPEM, pkey) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment