如何检查由CA颁发的PEM证书的有效性

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

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.

huangapple
  • 本文由 发表于 2017年8月31日 05:32:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/45970008.html
匿名

发表评论

匿名网友

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

确定