一、读取pfx文件获取公私钥
func TransferKey(path, password string) error {
content, err := ioutil.ReadFile(path)
if err != nil {
return fmt.Errorf("Read pfx file error %s ", err.Error())
}
blocks, err := pkcs12.ToPEM(content, password)
if err != nil {
return fmt.Errorf("pkcs12 decode error %s ", err.Error())
}
privateKey, err := os.Create("private.pem")
if err != nil {
return fmt.Errorf("Create private.pem error %s ", err.Error())
}
defer privateKey.Close()
publicKey, err := os.Create("public.pem")
if err != nil {
return fmt.Errorf("Create private.pem error %s ", err.Error())
}
defer publicKey.Close()
err = pem.Encode(privateKey, blocks[0])
if err != nil {
return err
}
err = pem.Encode(publicKey, blocks[1])
if err != nil {
return err
}
return nil
}
二、加载公私钥,构建https client
cliCrt, err := tls.LoadX509KeyPair("public.pem", "private.pem")
if err != nil {
fmt.Println(err)
}
tr := &http.Transport{
TLSClientConfig: &tls.Config{
Certificates: []tls.Certificate{cliCrt},
InsecureSkipVerify: true,
},
}
httpsclient := &http.Client{
Transport: tr,
}
三、若验证服务端证书
pool := x509.NewCertPool()
caPem: = "pem 格式"
pool.AppendCertsFromPEM([]byte(caPem))
tr := &http.Transport{
TLSClientConfig: &tls.Config{
Certificates: []tls.Certificate{cliCrt},
RootCAs: pool
InsecureSkipVerify: false,
},
}