go 获取证书信息

    • GO 获取 pem 证书信息

GO 获取 pem 证书信息

openssl 客户端查看证书信息:

[root@dnsserver test]# openssl x509 -noout -text -in ./client-release.pem
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number: 8536029279...
    Signature Algorithm: sha256WithRSAEncryption
        Issuer: C=US, O=Apple Inc., OU=Apple Worldwide Developer Relations, CN=Apple Worldwide Developer Relations Certification Authority
        Validity
            Not Before: Dec 11 07:15:05 2017 GMT
            Not After : Jan 10 07:15:05 2019 GMT
.....
.....

openssl 的 c 库获取 pem 格式的证书信息:

int parse_pem(const char* cert_file)
{
    BIO *b = BIO_new_file(cert_file, "rb");
    X509 * cert = PEM_read_bio_X509(b, NULL, NULL,NULL);
    BIO_free(b);
    if(cert==NULL)  return -1;
    ASN1_TIME *asn1_time = X509_get_notAfter(cert);
    int64_t after = ASN1_to_timestamp(asn1_time);
    printf("not after: %ld", after);
    X509_free(cert);
    return 0;
}

Go 语言获取 pem 格式证书信息:

func parsePemFile(path string) {
    certPEMBlock, err := ioutil.ReadFile(path)
    if err != nil {
        log.Fatalf(err)
            return
    }
    //获取证书信息 -----BEGIN CERTIFICATE-----   -----END CERTIFICATE-----
    //这里返回的第二个值是证书中剩余的 block, 一般是rsa私钥 也就是 -----BEGIN RSA PRIVATE KEY 部分
    //一般证书的有效期,组织信息等都在第一个部分里
    certDERBlock, _ := pem.Decode(certPEMBlock)
    if certDERBlock == nil {
        log.Fatalf(err)
        return
    }
    x509Cert, err := x509.ParseCertificate(certDERBlock.Bytes)
    if err != nil {
        log.Fatalf(err)
        return
    }
    log.Printf("certFile=%s, validation time %s ~ %s", path, 
    x509Cert.NotBefore.Format("2006-01-02 15:04"), x509Cert.NotAfter.Format("2006-01-02 15:04"))
}

证书生成过程可以参考 TLS with Go

你可能感兴趣的:(golang)