Go语言 如何使用Crypto 11解析证书/私钥对

3okqufwl  于 2023-02-01  发布在  Go
关注(0)|答案(1)|浏览(159)

我有一个仅包含私钥对象的pkcs11标记。我希望使用crypto11包检索私钥。当我尝试通过输入证书文件和私钥对象来解析x509密钥对时,收到错误。var pks *crypto11.SecretKey cannot convert pks (variable of type *crypto11.SecretKey) to []bytecompiler
我想知道检索私钥对象的正确方法是什么。我如何将crypto11包和证书文件转换为用于TLS连接的x509证书?

// Load the device certificate file
    certificate, err := ioutil.ReadFile("/PATH/cert.pem.crt")
    if err != nil {
        fmt.Println("Error loading device certificate:", err)
        return
    }
//Create Crypto11 instance
    ct11, err := crypto11.Configure(&crypto11.Config{
        Path: "/PATH/libsofthsm2.so",
        SlotNumber: #######,
        Pin:        "####",
    })
//Find Private key
    pks, err := ct11.FindKey(nil, []byte("MyPrivateKeyLabel"))
    if err != nil {
        log.Fatal("Could not search for private key: ", err)
    }

    //x509cert
    cert, err := tls.X509KeyPair(certificate, []byte(pks))
    if err != nil {
        log.Fatal("Error on X509Key Pair ", err)
    }
b4lqfgs4

b4lqfgs41#

解决方法很简单,我只需要把证书文件(pem crt)转换成der格式。

cerDer, cr := pem.Decode(certFile) //import "encoding/pem"

之后,我们可以解析证书文件:

cert, err := x509.ParseCertificate(cerDer.Bytes)

相关问题