英文:
How to check validity of PEM certificate issued by CA
问题
我有一个证书(PEM格式),我想检查该证书是否有效并由CA签名。我已经有了CA证书(PEM格式)。在Go语言中,使用标准的crypto/x509
包,有一种简单但安全的方法来检查证书。
英文:
I have a certificate (PEM), and I'd like to check if the certificate is valid and signed by CA. I already have the CA certificate (PEM). What is a simple, but secure way to check the certificate in Go, using the standard crypto/x509
package?
答案1
得分: 8
你需要使用Certificate.Verify()
。文档中有一个关于你想要做的事情的示例:
https://golang.org/pkg/crypto/x509/#example_Certificate_Verify
func verifyCert(rootPEM, certPEM string, name string) error {
roots := x509.NewCertPool()
ok := roots.AppendCertsFromPEM([]byte(rootPEM))
if !ok {
return fmt.Errorf("failed to parse root certificate")
}
block, _ := pem.Decode([]byte(certPEM))
if block == nil {
return fmt.Errorf("failed to parse certificate PEM")
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return fmt.Errorf("failed to parse certificate: %v", err.Error())
}
opts := x509.VerifyOptions{
DNSName: name,
Roots: roots,
}
if _, err := cert.Verify(opts); err != nil {
return fmt.Errorf("failed to verify certificate: %v", err.Error())
}
return nil
}
**免责声明:**我将其重新组织为一个函数,并删除了错误处理的恐慌。代码在其他方面与官方文档中的示例相同。
英文:
You need to use Certificate.Verify()
. There is an example for exactly what you want to do in the docs:
https://golang.org/pkg/crypto/x509/#example_Certificate_Verify
func verifyCert(rootPEM, certPEM string, name string) error {
roots := x509.NewCertPool()
ok := roots.AppendCertsFromPEM([]byte(rootPEM))
if !ok {
return fmt.Errorf("failed to parse root certificate")
}
block, _ := pem.Decode([]byte(certPEM))
if block == nil {
return fmt.Errorf("failed to parse certificate PEM")
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return fmt.Errorf("failed to parse certificate: %v", err.Error())
}
opts := x509.VerifyOptions{
DNSName: name,
Roots: roots,
}
if _, err := cert.Verify(opts); err != nil {
return fmt.Errorf("failed to verify certificate: %v", err.Error())
}
return nil
}
DISCLAIMER: I reorganized it as a function and removed the panics for error handling. The code is otherwise unchanged from the example in the official documentation.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论