2 回答
TA贡献1773条经验 获得超3个赞
tls.Certificate 通常存储证书链- 换句话说,> 1 个证书。请注意,它的Certificate
字段是类型[][]byte
,其中每个证书都是一个[]byte
.
tls 包导入了 x509 包,因此 x509 中没有获取 tls.Certificate 的函数;这将导致进口周期。但是如果你有一个 x509.Certificate,你就已经有一个 tls.Certificate;只需将 x509.Certificate 的Raw
字节放入 tls.Certificate 的Certificate
切片中。
TA贡献1796条经验 获得超7个赞
你可以这样做:
func LoadP12TLSCfg(keystore, password string) (*x509.CertPool, tls.Certificate, error) {
data, err := ioutil.ReadFile(keystore)
if err != nil {
return nil, tls.Certificate{}, err
}
pk, crt, caCrts, err := pkcs12.DecodeChain(data, password)
if err != nil {
return nil, tls.Certificate{}, err
}
pool := x509.NewCertPool()
pool.AddCert(caCrts[0])
tlsCrt := tls.Certificate{
Certificate: [][]byte{crt.Raw},
Leaf: crt,
PrivateKey: pk,
}
return pool, tlsCrt, nil
}
func LoadServerTLSCfg(keystore, password string) (*tls.Config, error) {
pool, crt, err := LoadP12TLSCfg(keystore, password)
if err != nil {
return nil, err
}
cfg := &tls.Config{
ClientCAs: pool,
ClientAuth: tls.RequireAndVerifyClientCert,
Certificates: []tls.Certificate{crt},
}
return cfg, nil
}
func LoadClientTLSCfg(keystore, password string, serverName string) (*tls.Config, error) {
pool, crt, err := LoadP12TLSCfg(keystore, password)
if err != nil {
return nil, err
}
cfg := &tls.Config{
RootCAs: pool,
Certificates: []tls.Certificate{crt},
ServerName: serverName,
}
return cfg, nil
}
- 2 回答
- 0 关注
- 255 浏览
添加回答
举报