1. 程式人生 > >x509: cannot validate certificate for x.x.x.x because it doesn't contain any IP SANs 解決:

x509: cannot validate certificate for x.x.x.x because it doesn't contain any IP SANs 解決:

x509: cannot validate certificate for x.x.x.x because it doesn't contain any IP SANs 解決:


一, 編輯openssl.cnf,在[v3_ca]下面新增:subjectAltName = IP:IP地址
    注意, 直接寫成123.56.157.144就行, 不用改成192或是其它地址

[ v3_ca ]

subjectAltName = IP:123.56.157.144


二, 生成證書相關檔案(伺服器單向認證如下)

1, openssl genrsa -out ca.key 2048 
2, openssl req -x509 -new -nodes -key ca.key -subj "/CN=tonybai.com" -days 5000 -out ca.crt

3, openssl genrsa -out server.key 2048 
4, openssl req -new -key server.key -subj "/CN=tonybai.com" -out server.csr
5, openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt -days 5000

第4步裡的tonybai.com就是程式碼裡要訪問的域名

三, 修改/etc/hosts 新增 192.168.1.41 tonybai.com
[[email protected]

my]# cat /etc/hosts

127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.1.41 tonybai.com

四, client程式碼如下:

package main

import (
    "crypto/tls"
    "crypto/x509"
    "fmt"
    "io/ioutil"
    "net/http"
)

func main() {
    pool := x509.NewCertPool()
    caCertPath := "ca.crt"

    caCrt, err := ioutil.ReadFile(caCertPath)
    if err != nil {
        fmt.Println("ReadFile err:", err)
        return
    }
    pool.AppendCertsFromPEM(caCrt)

    tr := &http.Transport{
        TLSClientConfig:    &tls.Config{RootCAs: pool},
        DisableCompression: true,
    }

    client := &http.Client{Transport: tr}

    
    //resp, err := client.Get("https://192.168.1.41:8081")
    //如果是IP則會報下面的錯
    //Get error: Get https://192.168.1.41:8000: x509: cannot validate certificate for 192.168.1.41 because it doesn't contain any IP SANs

    resp, err := client.Get("https://tonybai.com:8081")
    if err != nil {
        fmt.Println("Get error:", err)
        return
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    fmt.Println(string(body))
}

五, 伺服器程式碼如下
package main

import (
    "fmt"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w,
        "Hi, This is an example of http service in golang!")
}


func handler2(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w,
                "Hi, This is an example of http service in golang2222!")
}


func main() {

    http.HandleFunc("/h2", handler2)

    http.HandleFunc("/", handler)
    http.ListenAndServeTLS(":8081",
        "server.crt", "server.key", nil)
}