在使用自簽章伺服器憑證建立 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中文網其他相關文章!