dongwen7730 2016-08-08 06:45
浏览 232
已采纳

如何使用证书golang发送https请求

I have a server which has a rest API running over https. I want to make a call to this rest api in my application which is running in different port but since this is over https I am getting

Post https://localhost:8080/api/v1/myapi: x509: certificate signed by unknown authority

I have 2 files pulic_key.pem and private_key which can used to verify the certificate. How can verify certificate while sending rest request using golang? I am using &http.Client{} to send a rest request. Here is what I am doing to ignore the certificate right now.

tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}

client := &http.Client{Transport: tr}
  • 写回答

2条回答 默认 最新

  • dongwang788787 2016-08-08 09:26
    关注

    You need to add CA of your certificate to your transport like:

    package main
    
    import (
        "crypto/tls"
        "io/ioutil"
        "log"
        "net/http"
        "crypto/x509"
    )
    
    func main() {
        caCert, err := ioutil.ReadFile("rootCA.crt")
        if err != nil {
            log.Fatal(err)
        }
        caCertPool := x509.NewCertPool()
        caCertPool.AppendCertsFromPEM(caCert)
    
        client := &http.Client{
            Transport: &http.Transport{
                TLSClientConfig: &tls.Config{
                    RootCAs:      caCertPool,
                },
            },
        }
    
        _, err := client.Get("https://secure.domain.com")
        if err != nil {
            panic(err)
        }
    }
    

    But I guess you just haven't created CA to make your certificates. Here is the list of commands without explanation which can help you to make certificates signed with your own CA. For more information, you can Google it.

    1. Generating CA

      openssl genrsa -out rootCA.key 4096
      openssl req -x509 -new -key rootCA.key -days 3650 -out rootCA.crt
      
    2. Generate certificate for secure.domain.com signed with created CA

      openssl genrsa -out secure.domain.com.key 2048
      openssl req -new -key secure.domain.com.key -out secure.domain.com.csr
      #In answer to question `Common Name (e.g. server FQDN or YOUR name) []:` you should set `secure.domain.com` (your real domain name)
      openssl x509 -req -in secure.domain.com.csr -CA rootCA.crt -CAkey rootCA.key -CAcreateserial -days 365 -out secure.domain.com.crt
      
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 chaquopy python 安卓
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题