如何在 golang 中生成 x5t header 值

how to generate x5t header value in golang

我有一个 bash 命令(来自 medium)来生成证书指纹的 base64。

echo $(openssl x509 -in cert.pem -fingerprint -noout) | sed 's/SHA1 Fingerprint=//g' | sed 's/://g' | xxd -r -ps | base64

我想用golang写类似的代码。我在 xxd -r -ps 中遇到问题,如何在 golang 中实现这个 xxd?

命令的输出在Azure.

中用作x5theader

实现的代码-

data := `-----BEGIN CERTIFICATE-----
MIIDazCCAlOgAwIBAgIUDXiUCBmejBrKJeaF5xUltTKShokwDQYJKoZIhvcNAQEL
BQAwRTELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoM
GEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDAeFw0yMDA5MjAxMjA1MzdaFw0zMDA5
MTgxMjA1MzdaMEUxCzAJBgNVBAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEw
HwYDVQQKDBhJbnRlcm5ldCBXaWRnaXRzIFB0eSBMdGQwggEiMA0GCSqGSIb3DQEB
AQUAA4IBDwAwggEKAoIBAQDgZq1ucYX2Oi63TilhD8YPImV7CGPsjCPuIrsgaEV6
0fLVMp0lvDtnVsDWu4QGeBQN8cusOQclOje43AVmvUpAxKcXTRRvhxURpxnZqxXM
yYN7S+X5mO7sEj0DsAxpH8/Mo5awMi9e7rdEu2Q+IBQI0gZu+d3gv/svcKzPtwAj
kaZdsBhZr55vRigEJSaWTq8oRUdihQZVz9wqvwdIehh0SU61Awk8jmoDQ3+SocZo
cFEqsCqHasjKhXUOdQw24AsGIPjVN7IpBBWsQBgSVRY683ERKXE/pjGUDQJDuoEh
QVnWa3sf9/18tlnk+faCUjGAGsxZg1WJUez7fygQ+h0rAgMBAAGjUzBRMB0GA1Ud
DgQWBBROF0gDDord4phH0R8mtd/vTF2SgDAfBgNVHSMEGDAWgBROF0gDDord4phH
0R8mtd/vTF2SgDAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQDQ
hHU8RaekKQ332pq09TqIU1PvYb5/DTkPTftPX32g5/QPrIu1lSxdkByO1jK9MI/w
JECViCJdISK2FxW/74meXt4kALrebLc6HrLwYTqOR8PTAdtrGaPinKzrcjjB3oDK
Ni+qtW2GOGQ4MIqIgcVIqWNyuzVQ22BpKVbEvpzoMV1AcFAaHv4GpFxlKYrpxy4G
u0D84FHf95DPx6Jf79MRVh1WiEbsdWak8W1KAokRMp1AFktkZYDPGZvjuYD7jNfx
vcMgUpzdA0MYq54/OzypmN1tZ658EBkH6pCS8abtv6cZbEggQWI47TVov/THtBls
ySRtrOZbmIvnSs2ZMMsz
-----END CERTIFICATE-----
`
    derBytes, _ := pem.Decode([]byte(data))
    cert, err := x509.ParseCertificate(derBytes.Bytes)
    if err != nil {
        fmt.Println("err ParseCertificate", err)
    }
    fingerprint := sha1.Sum(cert.Raw)

    var buf bytes.Buffer
    for i, f := range fingerprint {
        if i > 0 {
            fmt.Fprintf(&buf, "")
        }
        fmt.Fprintf(&buf, "%02X", f)
    }
    fp := buf.String()
    fmt.Printf("Fingerprint : %s\n", fp) //04B9B0BCB18EF20440DE0ACEC010F6AD9F1B3A94

    // convert fp to byte and then enc in b64
    sEnc := base64.StdEncoding.EncodeToString([]byte(fp))
    fmt.Println(sEnc) //MDRCOUIwQkNCMThFRjIwNDQwREUwQUNFQzAxMEY2QUQ5RjFCM0E5NA==

openssl 命令的输出是BLmwvLGO8gRA3grOwBD2rZ8bOpQ= 程序的输出是 MDRCOUIwQkNCMThFRjIwNDQwREUwQUNFQzAxMEY2QUQ5RjFCM0E5NA==

您正在构建一个字节缓冲区,其中包含该字符串的十六进制表示和 base64 编码。相反,您需要对指纹的原始字节进行 base64 编码。

十六进制表示只是openssl的一个小技巧,没有对数据的十六进制表示进行任何操作。

将计算指纹后的代码替换为以下代码:

fingerprint := sha1.Sum(cert.Raw)

fmt.Printf("%x\n", fingerprint)
// 04b9b0bcb18ef20440de0acec010f6ad9f1b3a94

b64 := base64.StdEncoding.EncodeToString(fingerprint[:])
fmt.Println(b64)
// BLmwvLGO8gRA3grOwBD2rZ8bOpQ=

我们仍然可以用十六进制表示法打印指纹,我们只是使用%x动词。唯一有点烦人的是我们需要用fingerprint[:]把数组变成切片