golang:如何做一个带有错误证书的https请求? [英] golang: How to do a https request with bad certificate?

查看:441
本文介绍了golang:如何做一个带有错误证书的https请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想以编程方式获取 https://golang.org 。目前golang.org(ssl)有一个错误的证书发给 *。appspot.com 所以当我运行这个时:

 包主

导入(
记录
净/ http


func main(){
_,err:= http.Get(https://golang.org/)
if err!= nil {
log.Fatal (err)
}
}

我得到了(如我所料)

 获取https://golang.org/:证书适用于* .appspot.com,*。*。appspot.com ,appspot.com,而不是golang.org 

现在,我想亲自信任此证书(想象一下自我颁发的证书,我可以验证指纹等):我如何提出请求并验证/信任证书?

我可能需要使用openssl来下载证书,将它加载到我的文件中并填入 tls.Config struct!?

解决方案

安全提示:禁用s安全检查是危险的,应该避免使用



您可以针对默认客户端的所有请求全局禁用安全检查:

 软件包主要

导入(
fmt
net / http
加密/ tls


func main(){
http.DefaultTransport。(* http.Transport).TLSClientConfig =& tls.Config {InsecureSkipVerify:true}
_,err:= http.Get(https://golang.org/)
if err!= nil {
fmt.Println(err)
}
}

您可以禁用客户端的安全检查:

  package main 

import(
fmt
net / http
crypto / tls


func main(){
tr:=& http.Transport {
TLSClientConfig:& tls.Config {InsecureSkipVerify:true},

client:=& http.Client {Transport:tr}
_,err:= client.Get(https://golang.org/)
if err!= nil {
fmt.Println(err)
}
}


Say I want to get https://golang.org programatically. Currently golang.org (ssl) has a bad certificate which is issued to *.appspot.com So when I run this:

package main

import (
    "log"
    "net/http"
)

func main() {
    _, err := http.Get("https://golang.org/")
    if err != nil {
        log.Fatal(err)
    }
}

I get (as I expected)

Get https://golang.org/: certificate is valid for *.appspot.com, *.*.appspot.com, appspot.com, not golang.org

Now, I want to trust this certificate myself (imagine a self-issued certificate where I can validate fingerprint etc.): how can I make a request and validate/trust the certificate?

I probably need to use openssl to download the certificate, load it into my file and fill tls.Config struct !?

解决方案

Security note: Disabling security checks is dangerous and should be avoided

You can disable security checks globally for all requests of the default client:

package main

import (
    "fmt"
    "net/http"
    "crypto/tls"
)

func main() {
    http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
    _, err := http.Get("https://golang.org/")
    if err != nil {
        fmt.Println(err)
    }
}

You can disable security check for a client:

package main

import (
    "fmt"
    "net/http"
    "crypto/tls"
)

func main() {
    tr := &http.Transport{
        TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
    }
    client := &http.Client{Transport: tr}
    _, err := client.Get("https://golang.org/")
    if err != nil {
        fmt.Println(err)
    }
}

这篇关于golang:如何做一个带有错误证书的https请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆