certkit

package module
v1.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 27, 2026 License: Apache-2.0 Imports: 37 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

certkit

certkit 是统一的 X.509 证书工具包。公共能力集中在根包,支持证书、私钥、证书链和密钥库的解析、合并、转换、签发、吊销检查以及 TLS 服务探测。

环境要求

  • Go 1.27 或更高版本

安装

go get github.com/go-sdk/certkit

格式与算法

能力 支持范围
公钥算法 RSA、ECDSA、SM2
输入格式 PEM、DER、PKCS7/CMS 证书集合、PKCS12/PFX、JKS
输出格式 PEM、DER、PKCS7、PKCS12/PFX、JKS
CA 自签根 CA、中间 CA、终端证书、PKCS#10 CSR 签发、CRL 生成
吊销检查 CRL、OCSP、TLS stapled OCSP,包括 SM2 签名验证
TLS 探测 TLCP 1.1、TLS 1.0、1.1、1.2、1.3 独立握手和证书链验证

JCEKS 和 BKS 只进行格式识别,解析和输出返回 ErrUnsupportedFormat。TLCP 1.1(也称 GMSSL)支持携带 SNI 获取服务端签名证书、加密证书和证书链;SM2 证书也可独立解析、签发和执行 CRL/OCSP 验证。

打开和合并文件

Open 根据内容识别格式,不依赖文件扩展名:

store, err := certkit.Open(data, certkit.OpenOptions{
	Password: password,
})
if err != nil && !errx.Is(err, certkit.ErrPassword) {
	return err
}

Store 同时保存规范化后的证书、私钥以及原密钥库的条目关系:

type Store struct {
	Source       SourceInfo
	Entries      []*Entry
	Certificates []*Certificate
	PrivateKeys  []*PrivateKey
	Diagnostics  []Diagnostic
}

可以继续增加对象或合并其他文件:

err = store.AddCertificate(cert)
err = store.AddPrivateKey(key)
err = store.AddKeyPair("server", key, leaf, intermediate)
err = store.AddTrustedCertificate("root", root)
report, err := store.Add(otherData, certkit.OpenOptions{Password: otherPassword})

证书和私钥通过公钥 DER 指纹匹配。证书链使用签名、Issuer/Subject 和 AKI/SKI 关系排序。

证书链和私钥位于两个独立文件时,可以分别解析并获得匹配后的条目:

entry, err := certkit.OpenEntry(certificateData, privateKeyData, certkit.OpenOptions{
	Password: privateKeyPassword,
})
if err != nil {
	return err
}

certificatePEM, err := entry.CertificateChainPEM(certkit.EncodeOptions{
	ExcludeRootCertificates: true,
})
if err != nil {
	return err
}
privateKeyPEM, err := entry.PrivateKeyPEM(certkit.EncodeOptions{})
if err != nil {
	return err
}

OpenEntry 要求私钥输入中恰好包含一把可用私钥,并通过公钥判断它是否与证书链中的证书匹配;不匹配时返回 ErrKeyMismatch。返回条目的证书链按叶子证书、中间 CA 到根 CA 排序。输出私钥统一使用 PKCS#8 PEM。

JKS 密码和别名

  • 显式提供 store password 后,只使用该密码,不回退到其他候选。
  • 未提供 store password 时默认尝试 JDK 常用密码 changeit;设置 DisableJKSDefaultPassword 可以关闭。
  • private-key entry 优先使用 KeyPasswords[alias],之后调用 PasswordProvider,再尝试已经确认的 store password。
  • 密码探测失败但 JKS 条目边界可以安全解析时,返回部分 Store 和 ErrPassword。证书及 alias 被保留,私钥标记为 PrivateKeyStatusUnavailable,Source.IntegrityVerified 表示 store 完整性是否已经验证。
  • alias 比较不区分大小写,读取时保留原始写法。接受 X509 和 X.509 两种证书类型。
  • 单个未命名的新增条目输出 JKS 时使用 mykey;多个条目必须提供唯一 alias。
  • JKS 私钥统一以 PKCS#8 DER 写入。

错误可以通过 core/errx 判断:

if errx.Is(err, certkit.ErrPassword) {
	// store 可能仍包含可用的证书数据。
}

格式输出

output, report, err := store.Encode(certkit.FormatPKCS12, certkit.EncodeOptions{
	Password: []byte("explicit-password"),
	Alias:    "server",
})

JKS 和 PKCS12 不设置默认输出密码,必须显式提供非空密码。JKS 密码至少六个字节;未单独设置 KeyPassword 时使用显式提供的 store password。加密 PEM 同样需要显式密码。

PKCS12 的 RSA/ECDSA 编解码基于 SSLMate 安全修复版本,默认使用 Modern2026;国密 PKCS12 使用 emmansun 的 SM2/SM3/SM4 实现。PKCS7 私钥丢失、DER 多对象截断和单条目 PKCS12 选择等有损转换默认返回 ErrLossyConversion,只有 AllowLossy 为 true 时才允许。

两组上游的差异和本地补丁边界见 DEPENDENCIES.md。

创建和签发证书

root, err := certkit.CreateRootCA(certkit.RootCAOptions{
	Alias:   "root-ca",
	Subject: pkix.Name{CommonName: "Example Root CA"},
	Key:     certkit.KeyOptions{Algorithm: certkit.KeyAlgorithmRSA, RSABits: 3072},
})

intermediate, err := certkit.IssueCertificate(root, certkit.CertificateOptions{
	Alias:   "intermediate-ca",
	Subject: pkix.Name{CommonName: "Example Intermediate CA"},
	IsCA:    true,
	Key:     certkit.KeyOptions{Algorithm: certkit.KeyAlgorithmEC, Curve: "P-256"},
})

server, err := certkit.IssueCertificate(intermediate, certkit.CertificateOptions{
	Alias:    "server",
	Subject:  pkix.Name{CommonName: "example.com"},
	DNSNames: []string{"example.com"},
	Key:      certkit.KeyOptions{Algorithm: certkit.KeyAlgorithmSM2},
})

Entry 可以分别输出不含根证书的部署链、包含根证书的完整链以及 PKCS#8 私钥:

chainPEM, err := server.CertificateChainPEM(certkit.EncodeOptions{
	ExcludeRootCertificates: true,
})
chainWithRootPEM, err := server.CertificateChainPEM(certkit.EncodeOptions{})
privateKeyPEM, err := server.PrivateKeyPEM(certkit.EncodeOptions{})

两种证书链均保持叶子证书、中间 CA、根 CA 的既有顺序;无根链只剔除自签根证书。 私钥默认不加密;可以通过 EncryptPEMPrivateKey 和 Password 输出加密私钥。私钥输出包含敏感材料, 调用方负责限制访问并安全保存。

也可以使用 CreateCertificateRequest 创建 CSR,再用 SignCertificateRequest 签发外部公钥。

CRL 和 OCSP

纯验证方法不访问网络:

crlResult, err := certkit.CheckCRL(cert, issuer, crlData, certkit.CRLOptions{})
ocspResult, err := certkit.CheckOCSP(cert, issuer, responseData, certkit.OCSPOptions{})

显式网络方法从证书扩展中的第一个地址获取响应,并接受调用方提供的 context.Context 和 http.Client:

crlResult, err := certkit.FetchAndCheckCRL(ctx, client, cert, issuer, options)
ocspResult, err := certkit.FetchAndCheckOCSP(ctx, client, cert, issuer, options)

根证书

roots, err := certkit.SystemRoots()
roots, err = certkit.MozillaRoots()
roots, err = certkit.SystemAndMozillaRoots()
roots = certkit.CustomRoots(certificates...)

Mozilla 根来自 golang.org/x/crypto/x509roots/fallback/bundle 内嵌的 NSS 根集合,并在链验证时保留其额外约束。库不会修改进程级 x509.SetFallbackRoots。

TLS 探测

report, err := certkit.InspectTLS(
	ctx,
	"192.0.2.10:443",
	certkit.TLSOptions{
		ServerName: "example.com",
		Versions: []certkit.TLSVersion{
			certkit.TLS10,
			certkit.TLS11,
			certkit.TLS12,
			certkit.TLS13,
		},
		Roots: roots,
	},
)

每个 TLS 版本使用独立连接,并把 MinVersion 和 MaxVersion 固定为同一版本。握手成功、主机名匹配、信任链验证、服务端发送链完整性、根证书是否被多余发送以及 stapled OCSP 分别报告。根证书无需由服务端发送。

TLCP 1.1 必须显式加入版本列表,不会改变默认只探测 TLS 1.0–1.3 的行为:

report, err := certkit.InspectTLS(
	ctx,
	"192.0.2.10:443",
	certkit.TLSOptions{
		ServerName: "example.com",
		Versions:   []certkit.TLSVersion{certkit.TLCP11},
		Roots:      roots,
	},
)

TLCP ClientHello 会携带 ServerName 对应的 SNI。PeerCertificates.Certificates 按服务端消息顺序保存证书:第一个是签名证书,第二个是加密证书,其余为证书链;主机名和信任链验证同时覆盖两张叶子证书。

TLS 1.0/1.1 结果表示使用当前 Go 密码套件策略能否完成握手。库不会修改进程级 GODEBUG 来重新启用旧密码套件。

测试

默认测试使用运行时生成的证书和本地测试服务,不访问外网:

make test

它覆盖 RSA、ECDSA、SM2 CA 签发,交叉签名和多路径建链,PEM、DER、PKCS7、PKCS12、JKS 往返,密码错误的部分结果,CRL、OCSP、过期证书以及 TLS/TLCP SNI 和不完整链检测。

公网互操作测试默认跳过,需要显式启用:

CERTKIT_NETWORK_TESTS=1 make test-network

测试内容包括:

公网样本只保存在测试进程内,不写入仓库或日志。失败可能来自本地网络限制、证书轮换、样本迁移或代码回归,需要结合失败来源判断。

GitHub Actions 会在 lint 和默认测试通过后执行该测试;公网互操作步骤允许失败并产生 warning,不阻断工作流。

CRL 网络获取默认最多读取 16 MiB,OCSP 响应默认最多读取 1 MiB;调用方可以通过对应 Options 的 MaxSize 收紧或放宽限制。

开发约定

修改代码前先阅读 AGENTS.md、PROJECT_MAP.md、DEPENDENCIES.md 和本文件。发现文档与实现不一致时,应在同一次修改中更新。

make lint          # 整理依赖并执行 golangci-lint
make test          # 使用竞态检测运行本地确定性测试
make test-network  # 访问公开 CA 测试站点执行互操作测试

默认测试不得访问外网;make test-network 的结果受本地网络、公开 CA 服务状态、证书轮换和外部样本可用性影响。

Documentation

Overview

Package certkit 统一提供 X.509 证书、私钥和密钥库的解析、转换、签发、 吊销验证、信任根管理及 TLS 服务探测能力。

Open 根据文件内容识别 PEM、DER、PKCS7、PKCS12 和 JKS,不依赖文件扩展名。 Store 保存规范化后的证书、私钥及密钥库条目关系,并可继续增加对象或合并其他文件:

store, err := certkit.Open(data, certkit.OpenOptions{Password: password})
if err != nil && !errx.Is(err, certkit.ErrPassword) {
	return err
}
err = store.AddKeyPair("server", key, leaf, intermediate)

密码错误时,Open 会尽量返回已经安全解析的证书数据,并同时返回 ErrPassword。 调用方应使用 errx.Is 判断该错误;结构损坏和不支持格式使用各自的哨兵错误。 JCEKS 和 BKS 只进行格式识别,不提供解析和输出。

Store.Encode 输出 PEM、DER、PKCS7、PKCS12 或 JKS。PKCS12 和 JKS 不设置默认 输出密码,调用方必须通过 EncodeOptions 显式传入。可能丢弃证书或私钥的转换默认 返回 ErrLossyConversion,只有明确设置 AllowLossy 后才会执行。

CreateRootCA、IssueCertificate、CreateCertificateRequest 和 SignCertificateRequest 支持 RSA、ECDSA 和 SM2,可构造根 CA、中间 CA、终端证书 及 PKCS#10 CSR。CreateCRL、CheckCRL 和 CheckOCSP 提供本地吊销数据处理;仅 FetchAndCheckCRL 与 FetchAndCheckOCSP 会主动访问证书扩展中的网络地址。

SystemRoots、MozillaRoots、SystemAndMozillaRoots 和 CustomRoots 构造独立信任库。 MozillaRoots 使用内嵌的 Mozilla 根集合及其约束,不修改进程级根证书配置。

InspectTLS 按指定版本分别建立连接,支持显式探测 TLCP 1.1 以及 TLS 1.0、1.1、 1.2 和 1.3,报告 SNI、协商参数、服务端证书、主机名、信任链、链完整性及 stapled OCSP。TLCP 会收集并验证服务端签名证书和加密证书。

安装:

go get github.com/go-sdk/certkit

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrPassword 表示缺少密码或密码无法解密输入。
	ErrPassword = errx.New("password required or incorrect")
	// ErrUnsupportedFormat 表示已识别但未实现解析或输出的格式。
	ErrUnsupportedFormat = errx.New("unsupported certificate format")
	// ErrUnknownFormat 表示无法从内容判断输入格式。
	ErrUnknownFormat = errx.New("unknown certificate format")
	// ErrInvalidData 表示输入结构、边界或证书语义无效。
	ErrInvalidData = errx.New("invalid certificate data")
	// ErrKeyMismatch 表示私钥与证书公钥不匹配。
	ErrKeyMismatch = errx.New("private key does not match certificate")
	// ErrAliasConflict 表示密钥库 alias 重复。
	ErrAliasConflict = errx.New("alias already exists")
	// ErrLossyConversion 表示转换会丢弃证书或私钥。
	ErrLossyConversion = errx.New("conversion would discard data")
	// ErrNoCertificate 表示操作需要证书但 Store 中不存在可用证书。
	ErrNoCertificate = errx.New("certificate not found")
	// ErrNoPrivateKey 表示操作需要私钥但 Store 中不存在可用私钥。
	ErrNoPrivateKey = errx.New("private key not found")
	// ErrUnsupportedAlgorithm 表示请求的密码算法不受支持。
	ErrUnsupportedAlgorithm = errx.New("unsupported cryptographic algorithm")
)

Functions

func CreateCRL

func CreateCRL(issuer *Entry, options CreateCRLOptions) ([]byte, error)

CreateCRL 使用 CA 证书及私钥创建 DER 编码的 CRL。

func CreateCertificateRequest

func CreateCertificateRequest(key crypto.Signer, options CSROptions) ([]byte, error)

CreateCertificateRequest 使用现有私钥创建 DER 编码的 PKCS#10 CSR。

func GeneratePrivateKey

func GeneratePrivateKey(options KeyOptions) (crypto.Signer, error)

GeneratePrivateKey 生成配置指定的 RSA、ECDSA 或 SM2 私钥。

Types

type CRLOptions

type CRLOptions struct {
	CurrentTime  time.Time
	MaxClockSkew time.Duration
	MaxSize      int64
}

CRLOptions 配置 CRL 验证时间、时钟偏差和网络响应大小限制。

type CRLResult

type CRLResult struct {
	Revoked        bool
	ReasonCode     int
	RevocationTime time.Time
	ThisUpdate     time.Time
	NextUpdate     time.Time
	SignatureValid bool
	Fresh          bool
}

CRLResult 保存 CRL 签名、时效和证书吊销状态。

func CheckCRL

func CheckCRL(cert, issuer *smx509.Certificate, data []byte, options CRLOptions) (*CRLResult, error)

CheckCRL 在本地解析并验证 CRL,不访问网络。

func FetchAndCheckCRL

func FetchAndCheckCRL(ctx context.Context, client *http.Client, cert, issuer *smx509.Certificate, options CRLOptions) (*CRLResult, error)

FetchAndCheckCRL 获取证书首个 CRL 地址并验证响应。

type CSROptions

type CSROptions struct {
	Subject        pkix.Name
	DNSNames       []string
	IPAddresses    []net.IP
	EmailAddresses []string
	URIs           []*url.URL
}

CSROptions 配置 PKCS#10 CSR 的主题和 Subject Alternative Name。

type Certificate

type Certificate struct {
	ID          string
	Certificate *smx509.Certificate
	Role        CertificateRole
	Source      SourceRef
}

Certificate 保存规范化证书及其稳定标识和来源。

func NewCertificate

func NewCertificate(cert *smx509.Certificate) (*Certificate, error)

NewCertificate 将已解析证书规范化为 Store 使用的模型。

type CertificateOptions

type CertificateOptions struct {
	Alias          string
	Subject        pkix.Name
	NotBefore      time.Time
	NotAfter       time.Time
	ValidFor       time.Duration
	DNSNames       []string
	IPAddresses    []net.IP
	EmailAddresses []string
	URIs           []*url.URL
	IsCA           bool
	MaxPathLen     int
	MaxPathLenZero bool
	KeyUsage       smx509.KeyUsage
	ExtKeyUsage    []smx509.ExtKeyUsage
	SerialNumber   *big.Int
	Key            KeyOptions
}

CertificateOptions 配置 CA 或终端证书的主题、用途、有效期和密钥。

type CertificateRole

type CertificateRole string

CertificateRole 表示证书在链中的角色。

const (
	CertificateRoleUnknown      CertificateRole = "unknown"
	CertificateRoleLeaf         CertificateRole = "leaf"
	CertificateRoleIntermediate CertificateRole = "intermediate"
	CertificateRoleRoot         CertificateRole = "root"
)

type ChainValidation

type ChainValidation struct {
	HostnameValid       bool
	Trusted             bool
	ServedChainComplete bool
	ContainsRoot        bool
	MissingIssuers      []string
	CompletableViaAIA   bool
	Error               error
}

ChainValidation 保存主机名、信任链和服务端链完整性判断。

type Confidence

type Confidence string

Confidence 表示内容格式检测结果的可信程度。

const (
	ConfidenceLow    Confidence = "low"
	ConfidenceMedium Confidence = "medium"
	ConfidenceHigh   Confidence = "high"
)

type ConversionReport

type ConversionReport struct {
	Format                Format
	Aliases               []string
	CertificatesWritten   int
	PrivateKeysWritten    int
	DiscardedCertificates int
	DiscardedPrivateKeys  int
	Warnings              []string
}

ConversionReport 描述编码结果和被丢弃的对象。

type CreateCRLOptions

type CreateCRLOptions struct {
	Number       *big.Int
	ThisUpdate   time.Time
	NextUpdate   time.Time
	ValidFor     time.Duration
	Certificates []RevokedCertificate
}

CreateCRLOptions 配置 CRL 编号、有效期和吊销条目。

type Detection

type Detection struct {
	Format       Format
	Encoding     Encoding
	Confidence   Confidence
	Alternatives []Format
}

Detection 描述基于内容识别出的格式、编码和候选格式。

func Detect

func Detect(data []byte) (Detection, error)

Detect 根据内容识别证书或密钥容器格式,不依赖文件扩展名。

type Diagnostic

type Diagnostic struct {
	Level   DiagnosticLevel
	Code    string
	Message string
	Alias   string
}

Diagnostic 保存未中断处理流程的诊断信息。

type DiagnosticLevel

type DiagnosticLevel string

DiagnosticLevel 表示解析或转换诊断的严重程度。

const (
	DiagnosticInfo    DiagnosticLevel = "info"
	DiagnosticWarning DiagnosticLevel = "warning"
	DiagnosticError   DiagnosticLevel = "error"
)

type EncodeOptions

type EncodeOptions struct {
	Password                []byte
	KeyPassword             []byte
	KeyPasswords            map[string][]byte
	Alias                   string
	Aliases                 map[string]string
	AllowLossy              bool
	EncryptPEMPrivateKey    bool
	ExcludeRootCertificates bool
	PKCS12Profile           PKCS12Profile
}

EncodeOptions 配置目标格式的密码、alias、PEM 根证书选择和有损转换策略。

type Encoding

type Encoding string

Encoding 表示输入或输出的外层编码。

const (
	EncodingUnknown Encoding = "unknown"
	EncodingPEM     Encoding = "pem"
	EncodingDER     Encoding = "der"
)

type Entry

type Entry struct {
	Alias            string
	CreatedAt        time.Time
	PrivateKey       *PrivateKey
	PrivateKeyStatus PrivateKeyStatus
	Chain            []*Certificate
	Trusted          bool
}

Entry 保存 alias、私钥和有序证书链之间的关系。

func CreateRootCA

func CreateRootCA(options RootCAOptions) (*Entry, error)

CreateRootCA 创建自签根 CA 证书及其私钥。

func IssueCertificate

func IssueCertificate(issuer *Entry, options CertificateOptions) (*Entry, error)

IssueCertificate 使用 CA 生成新私钥并签发证书。

func OpenEntry added in v1.0.4

func OpenEntry(certificateData, privateKeyData []byte, options OpenOptions) (*Entry, error)

OpenEntry 分别解析证书链和私钥,并返回公钥匹配的条目。

func SignCertificateRequest

func SignCertificateRequest(issuer *Entry, requestData []byte, options CertificateOptions) (*Entry, error)

SignCertificateRequest 验证 PKCS#10 CSR 并使用 CA 签发证书。

func (*Entry) CertificateChainPEM added in v1.0.3

func (e *Entry) CertificateChainPEM(options EncodeOptions) ([]byte, error)

CertificateChainPEM 按叶子证书、中间 CA 到根 CA 的顺序输出 PEM 证书链。 EncodeOptions.ExcludeRootCertificates 用于控制是否剔除自签根证书。

func (*Entry) PrivateKeyPEM added in v1.0.3

func (e *Entry) PrivateKeyPEM(options EncodeOptions) ([]byte, error)

PrivateKeyPEM 将当前条目的可用私钥输出为 PKCS#8 PEM。 EncodeOptions.EncryptPEMPrivateKey 和 Password 用于控制私钥加密。

type Format

type Format string

Format 表示证书或密钥容器格式。

const (
	FormatAuto    Format = "auto"
	FormatUnknown Format = "unknown"
	FormatPEM     Format = "pem"
	FormatDER     Format = "der"
	FormatPKCS7   Format = "pkcs7"
	FormatPKCS12  Format = "pkcs12"
	FormatJKS     Format = "jks"
	FormatJCEKS   Format = "jceks"
	FormatBKS     Format = "bks"
)

type KeyAlgorithm

type KeyAlgorithm string

KeyAlgorithm 表示证书或私钥使用的公钥算法。

const (
	KeyAlgorithmUnknown KeyAlgorithm = "unknown"
	KeyAlgorithmRSA     KeyAlgorithm = "rsa"
	KeyAlgorithmEC      KeyAlgorithm = "ec"
	KeyAlgorithmSM2     KeyAlgorithm = "sm2"
)

type KeyOptions

type KeyOptions struct {
	Algorithm KeyAlgorithm
	RSABits   int
	Curve     string
}

KeyOptions 配置 RSA、ECDSA 或 SM2 私钥生成参数。

type MergeReport

type MergeReport struct {
	CertificatesAdded int
	PrivateKeysAdded  int
	EntriesAdded      int
}

MergeReport 记录 Store.Add 实际新增的对象数量。

type OCSPOptions

type OCSPOptions struct {
	CurrentTime  time.Time
	MaxClockSkew time.Duration
	Hash         crypto.Hash
	MaxSize      int64
}

OCSPOptions 配置 OCSP 验证时间、哈希算法和网络响应大小限制。

type OCSPResult

type OCSPResult struct {
	Status           int
	SerialNumber     string
	ProducedAt       time.Time
	ThisUpdate       time.Time
	NextUpdate       time.Time
	RevokedAt        time.Time
	RevocationReason int
	Fresh            bool
}

OCSPResult 保存 OCSP 响应中的状态和有效时间。

func CheckOCSP

func CheckOCSP(cert, issuer *smx509.Certificate, data []byte, options OCSPOptions) (*OCSPResult, error)

CheckOCSP 在本地解析并验证指定证书的 OCSP 响应。

func FetchAndCheckOCSP

func FetchAndCheckOCSP(ctx context.Context, client *http.Client, cert, issuer *smx509.Certificate, options OCSPOptions) (*OCSPResult, error)

FetchAndCheckOCSP 向证书首个 OCSP 地址发起请求并验证响应。

type OpenOptions

type OpenOptions struct {
	Format                    Format
	Password                  []byte
	KeyPasswords              map[string][]byte
	PasswordProvider          PasswordProvider
	DisableJKSDefaultPassword bool
	MaxInputSize              int
	MaxCertificates           int
	MaxPrivateKeys            int
}

OpenOptions 配置输入格式、密码来源和解析资源上限。

type PKCS12Profile

type PKCS12Profile string

PKCS12Profile 选择 PKCS12 的算法兼容配置。

const (
	PKCS12ProfileModern  PKCS12Profile = "modern"
	PKCS12ProfileLegacy  PKCS12Profile = "legacy"
	PKCS12ProfileShangMi PKCS12Profile = "shangmi"
)

type PasswordProvider

type PasswordProvider func(PasswordRequest) ([]byte, error)

PasswordProvider 根据解析上下文按需返回密码。

type PasswordPurpose

type PasswordPurpose string

PasswordPurpose 表示密码用于容器还是独立私钥。

const (
	PasswordPurposeContainer  PasswordPurpose = "container"
	PasswordPurposePrivateKey PasswordPurpose = "private_key"
)

type PasswordRequest

type PasswordRequest struct {
	Format  Format
	Alias   string
	Purpose PasswordPurpose
}

PasswordRequest 描述密码提供器当前需要的格式、alias 和用途。

type PrivateKey

type PrivateKey struct {
	ID         string
	Signer     crypto.Signer
	Algorithm  KeyAlgorithm
	Exportable bool
	Source     SourceRef
}

PrivateKey 保存可签名私钥及其稳定公钥标识。

func NewPrivateKey

func NewPrivateKey(key crypto.Signer) (*PrivateKey, error)

NewPrivateKey 将签名私钥规范化为 Store 使用的模型。

type PrivateKeyStatus

type PrivateKeyStatus string

PrivateKeyStatus 表示密钥库条目的私钥是否可用。

const (
	PrivateKeyStatusAvailable   PrivateKeyStatus = "available"
	PrivateKeyStatusUnavailable PrivateKeyStatus = "unavailable"
)

type RevokedCertificate

type RevokedCertificate struct {
	SerialNumber   *big.Int
	RevocationTime time.Time
	ReasonCode     int
}

RevokedCertificate 描述写入 CRL 的吊销证书条目。

type RootCAOptions

type RootCAOptions struct {
	Alias          string
	Subject        pkix.Name
	NotBefore      time.Time
	NotAfter       time.Time
	ValidFor       time.Duration
	MaxPathLen     int
	MaxPathLenZero bool
	Key            KeyOptions
}

RootCAOptions 配置自签根 CA 的主题、有效期、路径约束和密钥。

type SourceInfo

type SourceInfo struct {
	Format            Format
	Encoding          Encoding
	IntegrityVerified bool
}

SourceInfo 描述 Store 的来源格式和完整性状态。

type SourceRef

type SourceRef struct {
	Format Format
	Alias  string
	Index  int
}

SourceRef 记录证书或私钥在来源容器中的位置。

type Store

type Store struct {
	Source       SourceInfo
	Entries      []*Entry
	Certificates []*Certificate
	PrivateKeys  []*PrivateKey
	Diagnostics  []Diagnostic
}

Store 统一保存解析后的条目、证书、私钥和诊断信息。

func NewStore

func NewStore() *Store

NewStore 创建空的内存证书库。

func Open

func Open(data []byte, options OpenOptions) (*Store, error)

Open 根据内容或显式格式解析证书、私钥和密钥库。

func (*Store) Add

func (s *Store) Add(data []byte, options OpenOptions) (*MergeReport, error)

Add 解析输入并将对象合并到当前 Store。

func (*Store) AddCertificate

func (s *Store) AddCertificate(cert *smx509.Certificate) error

AddCertificate 向 Store 添加证书并重新匹配已有条目。

func (*Store) AddEntry

func (s *Store) AddEntry(entry *Entry) error

AddEntry 添加已经规范化的密钥库条目。

func (*Store) AddKeyPair

func (s *Store) AddKeyPair(alias string, key crypto.Signer, chain ...*smx509.Certificate) error

AddKeyPair 使用指定 alias 添加私钥及其有序证书链。

func (*Store) AddPrivateKey

func (s *Store) AddPrivateKey(key crypto.Signer) error

AddPrivateKey 向 Store 添加私钥并重新匹配已有条目。

func (*Store) AddTrustedCertificate

func (s *Store) AddTrustedCertificate(alias string, cert *smx509.Certificate) error

AddTrustedCertificate 使用指定 alias 添加信任证书条目。

func (*Store) Encode

func (s *Store) Encode(format Format, options EncodeOptions) ([]byte, *ConversionReport, error)

Encode 将 Store 编码为指定格式,并返回转换报告。

func (*Store) RemoveCertificate

func (s *Store) RemoveCertificate(id string) error

RemoveCertificate 按稳定标识移除证书及条目中的引用。

func (*Store) RemoveEntry

func (s *Store) RemoveEntry(alias string) error

RemoveEntry 按不区分大小写的 alias 移除条目。

func (*Store) RemovePrivateKey

func (s *Store) RemovePrivateKey(id string) error

RemovePrivateKey 按稳定标识移除私钥并保留不可用状态。

type TLSFailure

type TLSFailure struct {
	Stage   TLSFailureStage
	Message string
}

TLSFailure 保存单个协议版本的失败阶段和错误信息。

type TLSFailureStage

type TLSFailureStage string

TLSFailureStage 表示 TLCP 或 TLS 探测失败发生的阶段。

const (
	TLSFailureDial      TLSFailureStage = "dial"
	TLSFailureHandshake TLSFailureStage = "handshake"
	TLSFailureParse     TLSFailureStage = "certificate_parse"
)

type TLSOptions

type TLSOptions struct {
	ServerName   string
	Versions     []TLSVersion
	Roots        *TrustStore
	Dialer       *net.Dialer
	CipherSuites []uint16
	NextProtos   []string
	CurrentTime  time.Time
}

TLSOptions 配置 SNI、协议版本、信任根和连接参数。

type TLSReport

type TLSReport struct {
	Address    string
	ServerName string
	Versions   []TLSVersionResult
}

TLSReport 保存目标地址在各 TLCP 或 TLS 版本下的独立探测结果。

func InspectTLS

func InspectTLS(ctx context.Context, address string, options TLSOptions) (*TLSReport, error)

InspectTLS 对每个指定 TLCP 或 TLS 版本建立独立连接并验证服务端证书。

type TLSVersion

type TLSVersion uint16

TLSVersion 表示需要单独探测的 TLCP 或 TLS 协议版本。

func (TLSVersion) String

func (v TLSVersion) String() string

String 返回面向报告展示的 TLS 版本名称。

type TLSVersionResult

type TLSVersionResult struct {
	Version            TLSVersion
	HandshakeSucceeded bool
	NegotiatedVersion  uint16
	CipherSuite        uint16
	CipherSuiteName    string
	ALPN               string
	PeerCertificates   *Store
	Validation         ChainValidation
	StapledOCSP        *OCSPResult
	StapledOCSPError   error
	Failure            *TLSFailure
}

TLSVersionResult 保存单个 TLCP 或 TLS 版本的握手和证书验证结果。

type TrustStore

type TrustStore struct {
	// contains filtered or unexported fields
}

TrustStore 保存一个或多个互相独立的根证书池及其约束。

func CustomRoots

func CustomRoots(certs ...*smx509.Certificate) *TrustStore

CustomRoots 使用给定证书创建独立信任库。

func MozillaRoots

func MozillaRoots() (*TrustStore, error)

MozillaRoots 返回内嵌的 Mozilla 信任根及其约束。

func SystemAndMozillaRoots

func SystemAndMozillaRoots() (*TrustStore, error)

SystemAndMozillaRoots 返回同时包含系统和 Mozilla 根的独立信任库。

func SystemRoots

func SystemRoots() (*TrustStore, error)

SystemRoots 返回当前系统信任根。

func (*TrustStore) Add

func (t *TrustStore) Add(cert *smx509.Certificate)

Add 将证书加入自定义信任库的首个证书池。

type VerifyOptions

type VerifyOptions struct {
	Roots         *TrustStore
	Intermediates []*smx509.Certificate
	DNSName       string
	CurrentTime   time.Time
	KeyUsages     []smx509.ExtKeyUsage
}

VerifyOptions 配置证书链、主机名和验证时间。

type VerifyResult

type VerifyResult struct {
	Trusted       bool
	HostnameValid bool
	Chains        [][]*smx509.Certificate
	Error         error
}

VerifyResult 保存证书链和主机名验证结果。

func VerifyCertificate

func VerifyCertificate(cert *smx509.Certificate, options VerifyOptions) VerifyResult

VerifyCertificate 使用指定信任根和中间证书验证证书。

Directories

Path Synopsis
internal
ber
pkcs12
Package pkcs12 implements some of PKCS#12 (also known as P12 or PFX).
Package pkcs12 implements some of PKCS#12 (also known as P12 or PFX).
pkcs12/internal/rc2
Package rc2 implements the RC2 cipher
Package rc2 implements the RC2 cipher

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL