feat: add ExtractCertificatesFromPEM util func
This commit is contained in:
48
internal/pkg/utils/certs/extractor.go
Normal file
48
internal/pkg/utils/certs/extractor.go
Normal file
@@ -0,0 +1,48 @@
|
||||
package certs
|
||||
|
||||
import (
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
)
|
||||
|
||||
// 从 PEM 编码的证书字符串解析并提取服务器证书和中间证书。
|
||||
//
|
||||
// 入参:
|
||||
// - certPem: 证书 PEM 内容。
|
||||
//
|
||||
// 出参:
|
||||
// - serverCertPem: 服务器证书的 PEM 内容。
|
||||
// - interCertPem: 中间证书的 PEM 内容。
|
||||
// - err: 错误。
|
||||
func ExtractCertificatesFromPEM(certPem string) (serverCertPem string, interCertPem string, err error) {
|
||||
pemBlocks := make([]*pem.Block, 0)
|
||||
pemData := []byte(certPem)
|
||||
for {
|
||||
block, rest := pem.Decode(pemData)
|
||||
if block == nil || block.Type != "CERTIFICATE" {
|
||||
break
|
||||
}
|
||||
|
||||
pemBlocks = append(pemBlocks, block)
|
||||
pemData = rest
|
||||
}
|
||||
|
||||
serverCertPem = ""
|
||||
interCertPem = ""
|
||||
|
||||
if len(pemBlocks) == 0 {
|
||||
return "", "", errors.New("failed to decode PEM block")
|
||||
}
|
||||
|
||||
if len(pemBlocks) > 0 {
|
||||
serverCertPem = string(pem.EncodeToMemory(pemBlocks[0]))
|
||||
}
|
||||
|
||||
if len(pemBlocks) > 1 {
|
||||
for i := 1; i < len(pemBlocks); i++ {
|
||||
interCertPem += string(pem.EncodeToMemory(pemBlocks[i]))
|
||||
}
|
||||
}
|
||||
|
||||
return serverCertPem, interCertPem, nil
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
)
|
||||
|
||||
// 从 PEM 编码的证书字符串解析并返回一个 x509.Certificate 对象。
|
||||
// PEM 内容可能是包含多张证书的证书链,但只返回第一个证书(即服务器证书)。
|
||||
//
|
||||
// 入参:
|
||||
// - certPem: 证书 PEM 内容。
|
||||
|
||||
@@ -183,7 +183,7 @@ func GetValueOrDefaultAsBool(dict map[string]any, key string, defaultValue bool)
|
||||
return defaultValue
|
||||
}
|
||||
|
||||
// 将字典解码为指定类型的结构体。
|
||||
// 将字典填充到指定类型的结构体。
|
||||
// 与 [json.Unmarshal] 类似,但传入的是一个 [map[string]interface{}] 对象而非 JSON 格式的字符串。
|
||||
//
|
||||
// 入参:
|
||||
@@ -191,8 +191,8 @@ func GetValueOrDefaultAsBool(dict map[string]any, key string, defaultValue bool)
|
||||
// - output: 结构体指针。
|
||||
//
|
||||
// 出参:
|
||||
// - 错误信息。如果解码失败,则返回错误信息。
|
||||
func Decode(dict map[string]any, output any) error {
|
||||
// - 错误信息。如果填充失败,则返回错误信息。
|
||||
func Populate(dict map[string]any, output any) error {
|
||||
config := &mapstructure.DecoderConfig{
|
||||
Metadata: nil,
|
||||
Result: output,
|
||||
@@ -207,3 +207,8 @@ func Decode(dict map[string]any, output any) error {
|
||||
|
||||
return decoder.Decode(dict)
|
||||
}
|
||||
|
||||
// Deprecated: Use [Populate] instead.
|
||||
func Decode(dict map[string]any, output any) error {
|
||||
return Populate(dict, output)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user