去TLS连接

时间:2016-01-25 14:41:11

标签: ssl go tcp

我通过openssl连接到某个服务器:

openssl s_client -crlf -connect somehost.com:700 -cert key.pem

它有效。连接成功。

但是当我尝试从Go代码(文档中的示例)做同样的事情时,它对我不起作用:

import (
    "crypto/tls"
    "crypto/x509"
)

func main() {
    // Connecting with a custom root-certificate set.
    const rootPEM = `
-----BEGIN CERTIFICATE-----
my key text
-----END CERTIFICATE-----`

// First, create the set of root certificates. For this example we only
// have one. It's also possible to omit this in order to use the
// default root set of the current operating system.
roots := x509.NewCertPool()
ok := roots.AppendCertsFromPEM([]byte(rootPEM))
if !ok {
    panic("failed to parse root certificate")
}

conn, err := tls.Dial("tcp", "somehost.com:700", &tls.Config{
    RootCAs: roots,
})
if err != nil {
    panic("failed to connect: " + err.Error())
}
conn.Close()
}

我的文字错误是:

panic: failed to connect: x509: certificate is valid for otherhost.com, not somehost.com [recovered]

问题:我做错了什么?也许我没有添加一些tls.Config参数?

2 个答案:

答案 0 :(得分:2)

openssl s_client只是一个连接的测试工具,但如果证书对连接有效则无关紧要。如果证书可以被验证,则转而关注,因此您获得证书无效的信息,因为名称不匹配。

  

我做错了什么?

根据错误消息,您确实通过错误的主机名访问了主机。或者您已严重配置服务器,以便发送错​​误的证书。

答案 1 :(得分:0)

我不需要检查服务器的ssl证书。它是一些域名注册表的演示服务器。所以我需要服务器检查我的证书。

const certPEM = `-----BEGIN CERTIFICATE-----
-----END CERTIFICATE-----
`
const certKey = `-----BEGIN RSA PRIVATE KEY-----
-----END RSA PRIVATE KEY-----`

cert, err := tls.X509KeyPair([]byte(certPEM), []byte(certKey))
if err != nil {
    t.Error("server: loadkeys: %s", err)
}

cfg := tls.Config{
    InsecureSkipVerify: true,
    ServerName:         "somehost.com",
    Certificates:       []tls.Certificate{cert},
}

conn, err := tls.Dial("tcp", "somehost.com:700", &cfg)
if err != nil {
    t.Error("failed to connect: " + err.Error())
}

defer conn.Close()

所以这段代码适用于我的情况。

相关问题