How to parse certifcate/privateKey pair by using Crypto11

huangapple go评论90阅读模式
英文:

How to parse certifcate/privateKey pair by using Crypto11

问题

我有一个只包含私钥对象的pkcs11令牌。我想使用crypto11包来检索私钥。当我尝试通过输入证书文件和密钥对象来解析x509密钥对时,我收到了错误信息:var pks *crypto11.SecretKey 无法将pks(类型为*crypto11.SecretKey的变量)转换为[]byte编译器

我想知道检索私钥对象的正确方法是什么。以及如何将crypto11包和证书文件转换为用于TLS连接的x509证书?

// 加载设备证书文件
certificate, err := ioutil.ReadFile("/PATH/cert.pem.crt")
if err != nil {
    fmt.Println("加载设备证书时出错:", err)
    return
}

// 创建Crypto11实例
ct11, err := crypto11.Configure(&crypto11.Config{
    Path:       "/PATH/libsofthsm2.so",
    SlotNumber: #######,
    Pin:        "####",
})

// 查找私钥
pks, err := ct11.FindKey(nil, []byte("MyPrivateKeyLabel"))
if err != nil {
    log.Fatal("无法搜索私钥:", err)
}

// x509证书
cert, err := tls.X509KeyPair(certificate, []byte(pks))
if err != nil {
    log.Fatal("X509Key Pair错误:", err)
}
英文:

I have a pkcs11 token that only contains the private key object. I want to use crypto11 package to retrieve the private key. When I try to parse the x509 key pair by inputting the certificate file and the secret key object. I received the error. var pks *crypto11.SecretKey
cannot convert pks (variable of type *crypto11.SecretKey) to []bytecompiler

I want to know what is the correct way to retrieve the private key object. And How do I convert the crypto11 package and certificate file to the x509 certificate for TLS connection?

	// 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)
	}

答案1

得分: 1

解决方案非常简单。我只需要将证书文件(pem crt)转换为der格式。

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

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

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

The solution is pretty simple. I just need to convert the certificate file (pem crt) into the der format.

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

After that, we could parse the certificate file:

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

huangapple
  • 本文由 发表于 2023年1月30日 22:06:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/75285573.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定