You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Golang中解析X509证书为人类可读格式的问题

把X509证书转为人类可读格式的实用方法

嘿,我来帮你搞定这个问题!不管你是想快速查看证书信息,还是要在代码里解析处理,下面这些方法都能帮你把原本看起来像乱码或二进制的X509证书,转成清晰易懂的人类可读格式。

一、用OpenSSL命令行(最常用的快速方式)

如果你手里的证书是PEM格式(开头带-----BEGIN CERTIFICATE-----标记),直接用这条命令就能输出所有可读信息:

openssl x509 -in your_certificate.pem -text -noout
  • in:指定你的证书文件路径
  • text:核心参数,让OpenSSL输出人类可读的文本格式
  • noout:避免输出原始的证书二进制内容,只保留可读信息

如果是DER格式的二进制证书,不用先转格式,直接加-inform der参数就行:

openssl x509 -in your_certificate.der -inform der -text -noout

执行后你就能看到证书的版本、序列号、颁发者、主体、有效期、签名算法、扩展项等所有关键信息,一目了然。

二、用Python代码解析(适合程序内处理)

如果需要在Python项目里解析证书,用cryptography库是个省心的选择:
首先安装依赖(如果没装的话):

pip install cryptography

然后用这段代码读取并打印可读信息:

from cryptography import x509
from cryptography.hazmat.backends import default_backend

# 读取PEM格式证书
with open("your_certificate.pem", "rb") as cert_file:
    cert_data = cert_file.read()
cert = x509.load_pem_x509_certificate(cert_data, default_backend())

# 打印核心可读信息
print("证书版本:", cert.version.name)
print("序列号:", cert.serial_number)
print("颁发者:", cert.issuer.rfc4514_string())
print("主体:", cert.subject.rfc4514_string())
print("有效期起始时间:", cert.not_valid_before)
print("有效期截止时间:", cert.not_valid_after)

# 打印所有扩展项信息
print("\n=== 证书扩展项 ===")
for extension in cert.extensions:
    print(f"\n{extension.oid._name}:")
    print(extension.value)

要是处理DER格式证书,把load_pem_x509_certificate换成load_der_x509_certificate就行。

三、用Java代码解析

如果是Java项目,用JDK自带的证书处理API就能搞定,不需要额外依赖:

import java.io.FileInputStream;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

public class X509Reader {
    public static void main(String[] args) throws Exception {
        // 初始化X.509证书工厂
        CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
        
        // 读取证书文件(支持PEM和DER格式)
        try (FileInputStream inputStream = new FileInputStream("your_certificate.pem")) {
            X509Certificate cert = (X509Certificate) certFactory.generateCertificate(inputStream);
            
            // 输出可读信息
            System.out.println("证书版本: " + cert.getVersion());
            System.out.println("序列号: " + cert.getSerialNumber());
            System.out.println("颁发者: " + cert.getIssuerDN());
            System.out.println("主体: " + cert.getSubjectDN());
            System.out.println("有效期起始: " + cert.getNotBefore());
            System.out.println("有效期截止: " + cert.getNotAfter());
            System.out.println("签名算法: " + cert.getSigAlgName());
        }
    }
}

这些方法都能帮你把X509证书的内容转换成清晰的结构化信息,不管是日常排查问题还是程序开发都能用得上。

内容的提问来源于stack exchange,提问作者cybertextron

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:58:19