首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用“`certtostore`”从Golang的windows证书存储区获取证书时出错?

使用“`certtostore`”从Golang的windows证书存储区获取证书时出错?
EN

Stack Overflow用户
提问于 2022-06-02 08:46:12
回答 1查看 292关注 0票数 1

我想使用windows证书商店的证书包,谁能告诉我我在这里做了什么?

我的守则:

代码语言:javascript
复制
package main

import (
    "fmt"
    "runtime"

    "github.com/google/certtostore"
)

type certmgr struct {
    certToStore certtostore.CertStorage
}

func main() {
    if runtime.GOOS == "windows" {
        var cert certmgr
        certInStore, err := cert.certToStore.Cert()
        if err != nil {
            fmt.Println("message", "Error in getting system store certificate ...")
        }

        fmt.Println("Windows System Store Certificate", *certInStore)

    }
}

我所犯的错误:

代码语言:javascript
复制
panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xc0000005 code=0x0 addr=0x0 pc=0xbe2dda]

goroutine 1 [running]:
main.main()
        C:/Users/prajwal.bhagat/go/src/phoenix/mainsvc/cmd/main/test.go:17 +0x1a
exit status 2
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-06-02 09:29:50

您可以使用像google/certtostore这样的库,它是一个多平台包,允许您在Linux上使用x509证书,在Windows上使用证书存储。

它不直接获取证书包,而是使用打电话,它从结束证书开始构建证书链上下文,并在可能的情况下返回到可信根CA

它由CertWithContext()使用,它使用创建WinCertStore时提供的颁发者值执行证书查找。

它返回证书及其Windows,该上下文可用于执行其他操作,例如使用CertKey()查找私钥。

无效的内存地址或零指针取消引用

您需要初始化var cert certmgr

更广泛地说,您需要首先获得商店,如在这个例子

代码语言:javascript
复制
    fmt.Println("open cert store")

    // Open the local cert store. Provider generally shouldn't matter, so use Software which is ubiquitous. See comments in getHostKey.
    store, err := certtostore.OpenWinCertStore(certtostore.ProviderMSSoftware, "", []string{"localhost"}, nil, false)
    
    if err != nil {
        fmt.Errorf("OpenWinCertStore: %v", err)
        return
    }   
    
    fmt.Println("get cert from cert store")
    // Obtain the first cert matching all of container/issuers/intermediates in the store.
    // This function is indifferent to the provider the store was opened with, as the store lists certs
    // from all providers.
    crt, context, err := store.CertWithContext()
    if err != nil {
        fmt.Println("failed to get cert from cert store. ", err)
        return
    }
    
    if crt == nil {
        fmt.Println("no cert")
        return
    }

    fmt.Println("get key from cert")
    // Obtain the private key from the cert. This *should* work regardless of provider because
    // the key is directly linked to the certificate.
    key, err := store.CertKey(context)
    if err != nil {
        fmt.Printf("private key not found in %s, %s", store.ProvName, err)
        return
    }

    if key == nil {
        fmt.Println("no key")
        return
    }

    fmt.Printf("find cert '%s' with private key in container '%s', algo '%s'\n", crt.Subject, key.Container, key.AlgorithmGroup)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72473312

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档