如何显示网站证书的公钥

时间:2019-01-27 00:37:12

标签: ssl go ssl-certificate

我创建了一个Go程序来连接到网站并获取其使用的证书。我不确定如何正确表示公钥。

我可以获取证书,并且可以在Certificate.PublicKey上键入check。一旦了解了rsa.PublicKey或ecdsa.PublicKey,我就需要打印它的十六进制表示形式。

switch cert.PublicKey.(type) {
case *rsa.PublicKey:
    logrus.Error("this is RSA")
    // TODO: print hex representation of key
case *ecdsa.PublicKey:
    logrus.Error("this is ECDSA")
    // TODO: print hex representation of key
default:
    fmt.Println("it's something else")
}

我希望它会打印出类似的内容:

04 4B F9 47 1B A8 A8 CB A4 C6 C0 2D 45 DE 43 F3 BC F5 D2 98 F4 25 90 6F 13 0D 78 1A AC 05 B4 DF 7B F6 06 5C 80 97 9A 53 06 D0 DB 0E 15 AD 03 DE 14 09 D3 77 54 B1 4E 15 A8 AF E3 FD DC 9D AD E0 C5

1 个答案:

答案 0 :(得分:2)

似乎您要索取所涉及证书的sha1总和。 这是一个要求提供host:port并打印所涉及证书总和的有效示例

import QtQuick 2.0
import QtQuick.Window 2.0
import QtLocation 5.6
import QtPositioning 5.6

Window {
    width: 512
    height: 512
    visible: true

    property variant loc: QtPositioning.coordinate(48.858222, 2.2945)

    Map {
        id: map
        anchors.fill: parent
        plugin: Plugin { name: "osm" }
        center: loc
        zoomLevel: 16

        MapQuickItem {
            id: arrow
            coordinate: loc
            NumberAnimation on rotation { from: 0; to: 360; duration: 2000; loops: Animation.Infinite; }
            anchorPoint.x: img.width/2
            anchorPoint.y: img.height/2
            sourceItem: Image {
                id: img
                source: "arrow.png"
            }
        }
    }
}

运行方式:

package main

import (
        "crypto/sha1"
        "crypto/tls"
        "fmt"
        "log"
        "os"
)

func main() {
        if len(os.Args) != 2 {
                log.Panic("call with argument of host:port")
        }
        log.SetFlags(log.Lshortfile)

        conf := &tls.Config{
                //InsecureSkipVerify: true,
        }
        fmt.Printf("dialing:%s\n", os.Args[1])
        conn, err := tls.Dial("tcp", os.Args[1], conf)
        if err != nil {
                log.Println(err)
                return
        }
        defer conn.Close()
        for i, v := range conn.ConnectionState().PeerCertificates {
                //edit: use %X for uppercase hex printing
                fmt.Printf("cert %d sha1 fingerprint:%x \n", i, sha1.Sum(v.Raw))
        }
}

对于SSL的一般概念,我发现this stackexchange answer非常有价值。