
我正在尝试通过 golang x509 包为 https 服务器制作 tls 证书
我收到了这个错误
tls: failed to find any pem data in certificate input
经过一番研究,我像这样创建了我的证书
func generatecert() {
ca := &x509.certificate{
serialnumber: big.newint(2023),
subject: pkix.name{
organization: []string{"company"},
organizationalunit: []string{"lol"},
country: []string{"us"},
province: []string{""},
locality: []string{"ny"},
streetaddress: []string{"no street"},
postalcode: []string{"77777"},
},
notbefore: time.now(),
notafter: time.now().adddate(10, 0, 0),
subjectkeyid: []byte{1, 2, 3, 4, 5},
basicconstraintsvalid: true,
isca: true,
extkeyusage: []x509.extkeyusage{x509.extkeyusageclientauth, x509.extkeyusageserverauth},
keyusage: x509.keyusagedigitalsignature | x509.keyusagecertsign,
}
certpubl, certpriv, err := ed25519.generatekey(rand.reader)
if err != nil {
log.println("key generate failed", err)
return
}
certcert, err := x509.createcertificate(rand.reader, ca, ca, certpubl, certpriv)
if err != nil {
log.println("create cert failed", err)
return
}
out := &bytes.buffer{}
//encoding cert
certtestpem := &pem.block{type: "certificate", bytes: certcert}
pem.encode(out, certtestpem)
publiccert := out.bytes()
certderblock, publiccert := pem.decode(publiccert)
//check decoded cert
print(certderblock.type, "\n")
if publiccert != nil {
print("publiccert nil\n")
}
//encoding private key
out.reset()
privatepem, _ := x509.marshalpkcs8privatekey(certpriv)
pem.encode(out, &pem.block{type: "private key", bytes: privatepem})
privitkey := out.bytes()
//check keypair
_, err = tls.x509keypair(publiccert, privitkey)
if err != nil {
print(err.error())
}
}它显示如下错误
CERTIFICATE publicCert nil tls: failed to find any PEM data in certificate input
我尝试在 pem.encodetomemory 之后解码
pem.type 是正确的,但变量“publiccert”为零,我尝试添加 \n 证书的开头,它什么也没做,但证书本身不为零,有人可以帮助我吗 p>
我该如何做才能使 tls 正常工作???
这段代码有几个问题
publiccert := out.bytes()
现阶段检查publiccert的内容显示了期望值。但以下语句将简单地覆盖 publiccert:
certderblock, publiccert := pem.decode(publiccert)
通过检查此语句后的 publiccert 可以看到这一点。 如文档所述 publiccert 现在将在实际证书之后显示数据。
应该是这样
certderblock, _ := pem.decode(publiccert)
检查此更正语句后的 publiccert 内容再次显示预期值。
out.reset()
privatepem, _ := x509.marshalpkcs8privatekey(certpriv)
pem.encode(out, &pem.block{type: "private key", bytes: privatepem})
privitkey := out.bytes()这会将预期值获取到 privitkey 中。但是,它将更改 publiccert,因为它只是 out 的一部分,并且 out 已更改操作。因此,out 现在将在开头包含 privitkey,而不再是证书的开头 - 这反映在 publiccert 的值中。
切片仅在下一次缓冲区修改之前有效(即,仅在下次调用 read、write、reset 或 truncate 等方法之前有效)
因此,不仅仅是重置现有缓冲区
out.reset()
最好为 privitkey 创建一个新缓冲区,并为 publiccert 保留现有缓冲区
out = &bytes.Buffer{}以上就是tls.X509KeyPair 弹出“无法在证书输入中找到任何 PEM 数据”错误的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号