如何解析 PEM 证书的集合
How to parse collection of PEM certs
我有一个字符串形式的 pem 证书集合,我想将其绑定到 TLS 端点,如何有效地将它们转换为 CRT 文件 (i.e.public.crt) 和密钥文件(即 private.key),用于将其绑定到端点:
输入字符串:
-----BEGIN PRIVATE KEY-----
MIIE3oydueOANJHhvL3yvJdTphoev5GO7go+ByYOO/l54u5O2PxMeX+AjAb6Axmq
livIuhw=
-----END PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
MIIE3oydueOANJHhvL3yvJdTphoev5GO7go+ByYOO/l54u5O2PxMeX+AjAb6Axmq
livIuhw=
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
MIIE3oydueOANJHhvL3yvJdTphoev5GO7go+ByYOO/l54u5O2PxMeX+AjAb6Axmq
asdsa312asdsadasdsad=
-----END CERTIFICATE-----
我的绑定代码是:
https_r := mux.NewRouter()
err_https := http.ListenAndServeTLS(serviceEndpoint, "/etc/pki/tls/certs/public.crt", "/etc/pki/tls/certs/private.key", https_r)
if err_https != nil {
log.Fatal("Web server (HTTPS): ", err_https)
}
我尝试了两种方法:
理想情况下,我不想执行一堆字符串解析,这很容易中断。
任何其他方式将不胜感激。
I tried to decode it to a PEM block, but it only reads one of the certs and drops the rest.
诀窍是处理其余的 PEM 块。它在 pem.Decode
秒内返回结果。这是如何完成的:
for block, rest := pem.Decode(data); block != nil; block, rest = pem.Decode(rest) {
switch block.Type {
case "CERTIFICATE":
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
panic(err)
}
// Handle certificate
fmt.Printf("%T %#v\n", cert, cert)
case "PRIVATE KEY":
key, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
panic(err)
}
// Handle private key
fmt.Printf("%T %#v\n", key, key)
default:
panic("unknown block type")
}
}
我有一个字符串形式的 pem 证书集合,我想将其绑定到 TLS 端点,如何有效地将它们转换为 CRT 文件 (i.e.public.crt) 和密钥文件(即 private.key),用于将其绑定到端点:
输入字符串:
-----BEGIN PRIVATE KEY-----
MIIE3oydueOANJHhvL3yvJdTphoev5GO7go+ByYOO/l54u5O2PxMeX+AjAb6Axmq
livIuhw=
-----END PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
MIIE3oydueOANJHhvL3yvJdTphoev5GO7go+ByYOO/l54u5O2PxMeX+AjAb6Axmq
livIuhw=
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
MIIE3oydueOANJHhvL3yvJdTphoev5GO7go+ByYOO/l54u5O2PxMeX+AjAb6Axmq
asdsa312asdsadasdsad=
-----END CERTIFICATE-----
我的绑定代码是:
https_r := mux.NewRouter()
err_https := http.ListenAndServeTLS(serviceEndpoint, "/etc/pki/tls/certs/public.crt", "/etc/pki/tls/certs/private.key", https_r)
if err_https != nil {
log.Fatal("Web server (HTTPS): ", err_https)
}
我尝试了两种方法:
理想情况下,我不想执行一堆字符串解析,这很容易中断。
任何其他方式将不胜感激。
I tried to decode it to a PEM block, but it only reads one of the certs and drops the rest.
诀窍是处理其余的 PEM 块。它在 pem.Decode
秒内返回结果。这是如何完成的:
for block, rest := pem.Decode(data); block != nil; block, rest = pem.Decode(rest) {
switch block.Type {
case "CERTIFICATE":
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
panic(err)
}
// Handle certificate
fmt.Printf("%T %#v\n", cert, cert)
case "PRIVATE KEY":
key, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
panic(err)
}
// Handle private key
fmt.Printf("%T %#v\n", key, key)
default:
panic("unknown block type")
}
}