go - 在 Go 中生成 X.509 证书时出错

标签 go x509certificate

我是 Go 的新手,我正在尝试使用以下代码生成 X.509 证书:

cert, err := x509.CreateCertificate(
    random,
    &certTemplate,
    cert,
    publicKey,
    privateKey
)

其中 publicKey 变量的类型为 interface{},它是调用 x509.ParsePKIXPublicKey(bytes) 的结果。

我遇到的错误是:

x509:仅支持 RSA 和 ECDSA 公钥

我得出的结论是,这是将类型为 interface{} 的 publicKey 传递给 x509.CreateCertificate 函数的结果,因为它与该函数内的类型开关不匹配。我尝试传递 &publicKey 结果相同。我还尝试使用 publicKey 进行类型断言,如下所示:

var pk *ecdsa.PublicKey
pk = publicKey.(*ecdsa.PublicKey)

cert, err := x509.CreateCertificate(
    random,
    &certTemplate,
    cert,
    pk,
    privateKey
)

但随后出现此错误: panic :接口(interface)转换:接口(interface) {} 为零,而不是 *ecdsa.PublicKey 如果我将 &pk 作为参数传递,则会发生相同的错误。

这是我生成公钥的方式:

// Generate key pair
curve := elliptic.P384()
privateKey := new(ecdsa.PrivateKey)
privateKey, err := ecdsa.GenerateKey(curve, rand.Reader)
publicKey := &privatekey.PublicKey

// Obtain bytes from public key for communication using protobuf
publicKeyBytes, err := x509.MarshalPKIXPublicKey(publicKey)

// Protobuf communication takes place here

receivedPublicKey, err := x509.ParsePKIXPublicKey(publicKeyBytes)

// verification of public key here (the verification ends successfully)
// populate X.509 template

// create certificate
certificate, err := x509.CreateCertificate(
    random,
    &certificateTemplate,
    certificate,
    receivedPublicKey,
    privateKey,
)

如果有人能给我指出正确的方向或知道如何解决这个问题,那将非常有帮助。提前致谢!

最佳答案

我让它工作,做这样的事情:

// Generate key pair
curve := elliptic.P384()
//privateKey := new(ecdsa.PrivateKey)
privateKey, err := ecdsa.GenerateKey(curve, rand.Reader)
publicKey := &privateKey.PublicKey

其余部分与您所写的完全一致,看看您是否可以镜像并使其正常工作。

关于go - 在 Go 中生成 X.509 证书时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33789680/

相关文章:

templates - 如何在 Go html/template 中获取 map 元素的结构字段?

json - 处理两种形式的 JSON?

openssl - 在 CentOS linux 中创建 CA 时权限被拒绝

c# - 当您知道无效证书是安全的时,测试 X509Certificate.Thumbprint 属性是否安全?

go - 学习Golang的人应该注意哪些常见的 "Go-tchas"?

java - Go 的等价于 'throws' 的子句是什么?

java - Google Cloud Function可自动创建Windows vm密码

c# - 根据自签名证书颁发机构验证服务器证书

ldap - 在 inetOrgPerson 的 userSMIMECertificate 属性中添加证书

java.security.cert.CertificateException : Could not parse certificate: java. io.IOException : Invalid BER/DER data (too huge? )