[英]Get remote ssl certificate in golang
我想通過 TLS 接收 TCP 連接。 我想驗證客戶端證書並使用它來驗證客戶端到我的應用程序。 Go 有標准的crypto/tls
包。 它可以驗證客戶端/服務器證書。 但是我找不到獲取遠程(客戶端)證書詳細信息的方法,例如通用名稱。
必須調用crypto/tls/Conn.Handshake 。 然后你可以讀取對等證書:tlsconn.ConnectionState().PeerCertificates[0].Subject.CommonName
以下代碼可能會幫助您獲得答案
package main
import (
"crypto/tls"
"fmt"
"log"
)
func main() {
conf := &tls.Config{
InsecureSkipVerify: true,
}
conn, err := tls.Dial("tcp", "www.google.com:443", conf)
if err != nil {
log.Println("Error in Dial", err)
return
}
defer conn.Close()
certs := conn.ConnectionState().PeerCertificates
for _, cert := range certs {
fmt.Printf("Issuer Name: %s\n", cert.Issuer)
fmt.Printf("Expiry: %s \n", cert.NotAfter.Format("2006-January-02"))
fmt.Printf("Common Name: %s \n", cert.Issuer.CommonName)
}
}
使用crypto/tls 時,您可以查詢 ConnectionState 的任何 Conn 對象:
func (c *Conn) ConnectionState() ConnectionState
ConnectionState 結構包含有關客戶端證書的信息:
type ConnectionState struct {
PeerCertificates []*x509.Certificate // certificate chain presented by remote peer
}
x509.Certificate應該很容易使用。
在服務器請求客戶端身份驗證之前,您必須使用服務器證書、客戶端 CA(否則您必須手動驗證信任鏈,您真的不想要)和 tls.RequireAndVerifyClientCert 配置連接。 例如:
// Load my SSL key and certificate
cert, err := tls.LoadX509KeyPair(settings.MyCertificateFile, settings.MyKeyFile)
checkError(err, "LoadX509KeyPair")
// Load the CA certificate for client certificate validation
capool := x509.NewCertPool()
cacert, err := ioutil.ReadFile(settings.CAKeyFile)
checkError(err, "loadCACert")
capool.AppendCertsFromPEM(cacert)
// Prepare server configuration
config := tls.Config{Certificates: []tls.Certificate{cert}, ClientCAs: capool, ClientAuth: tls.RequireAndVerifyClientCert}
config.NextProtos = []string{"http/1.1"}
config.Rand = rand.Reader
有一種更簡單的方法可以做到這一點:
func renewCert(w http.ResponseWriter, r *http.Request) {
if r.TLS != nil && len(r.TLS.PeerCertificates) > 0 {
cn := strings.ToLower(r.TLS.PeerCertificates[0].Subject.CommonName)
fmt.Println("CN: %s", cn)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.