首頁 >後端開發 >Golang >使用自簽章 TLS 憑證時如何解決「x509:憑證由未知授權單位簽署」錯誤?

使用自簽章 TLS 憑證時如何解決「x509:憑證由未知授權單位簽署」錯誤?

Patricia Arquette
Patricia Arquette原創
2024-12-09 21:30:11434瀏覽

How to Resolve the

使用自簽名憑證設定 TLS

在使用自簽章伺服器憑證建立 TLS 連線時,使用者經常會遇到「x509: 憑證由未知權限」錯誤。當用戶端無法將自簽名憑證識別為可信任機構時,就會出現此問題。

要解決此錯誤,問題出在證書產生過程。提供的程式碼片段會建立一個自簽名證書,但忽略設定「IsCA:true」標誌。此標誌將憑證指定為憑證授權單位 (CA),使其能夠簽署其他憑證。

修正後的程式碼應類似下列內容:

產生憑證:

func generateCertificate() {
    key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
    if err != nil {
        log.Fatal(err)
    }

    subject := x509.Certificate{
        SerialNumber: big.NewInt(42),
        Subject: pkix.Name{
            Organization: []string{"My Organization"},
        },
    }

    template := x509.Certificate{
        SerialNumber: big.NewInt(43),
        Subject:      subject.Subject,
        KeyUsage: x509.KeyUsageCertSign,
        IsCA:        true, // Setting IsCA to true designates the certificate as a CA
        ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
    }

    cert, err := x509.CreateCertificate(rand.Reader, &template, &template, &key.PublicKey, key)
    if err != nil {
        log.Fatal(err)
    }

    // Save the certificate and key to pem files
}

客戶設定:

func clientSetup() (*tls.Config, error) {
    cert, err := ioutil.ReadFile("./cert.pem")
    if err != nil {
        return nil, err
    }

    certpool := x509.NewCertPool()
    certpool.AppendCertsFromPEM(cert)

    config := &tls.Config{
        RootCAs:    certpool,
        InsecureSkipVerify: true, //!!! Skip certificate verification for testing purposes only
    }

    return config, nil
}

注意:對於生產環境,應啟用憑證驗證,以確保伺服器的真實性。

以上是使用自簽章 TLS 憑證時如何解決「x509:憑證由未知授權單位簽署」錯誤?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn