有证书发送https请求

有证书发送https请求,第1张

一、读取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,
		},
	}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/994451.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存