core

package
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Jan 30, 2026 License: MIT Imports: 25 Imported by: 0

Documentation

Overview

Package core 提供 X.509 证书生成, 签发, 验证和管理功能.

Index

Constants

View Source
const (
	HashAlgoSHA256 = "sha256"
	HashAlgoSHA384 = "sha384"
	HashAlgoSHA512 = "sha512"
)

支持的哈希算法.

Variables

View Source
var (
	// ErrNoPrivateKey 没有私钥.
	ErrNoPrivateKey = errors.New("no private key available")

	// ErrInvalidKeyType 无效的密钥类型.
	ErrInvalidKeyType = errors.New("invalid key type for this operation")

	// ErrInvalidCiphertext 无效的密文.
	ErrInvalidCiphertext = errors.New("invalid ciphertext")

	// ErrInvalidSignature 无效的签名.
	ErrInvalidSignature = errors.New("invalid signature")
)

错误定义.

View Source
var (
	ErrDaysValidRequired    = errors.New("days valid is required and must be > 0")
	ErrKeyAlgorithmRequired = errors.New("key algorithm is required")
	ErrRSAKeyBitsRequired   = errors.New("RSA key bits is required when using RSA algorithm")
	ErrECDSACurveRequired   = errors.New("ECDSA curve is required when using ECDSA algorithm")
	ErrNameRequired         = errors.New("name is required")
	ErrCACertRequired       = errors.New("CA certificate is required")
	ErrCAKeyRequired        = errors.New("CA private key is required")
	ErrCSRRequired          = errors.New("CSR is required")
	ErrCertRequired         = errors.New("certificate is required")
	ErrPrivateKeyRequired   = errors.New("private key is required")
	ErrRevokedCertsRequired = errors.New("revoked certificates list is required")
)

配置验证错误定义.

Functions

func BuildCertChain

func BuildCertChain(cfg *CertChainConfig) error

BuildCertChain 根据配置构建证书链.

func DecodeCertFromHeader

func DecodeCertFromHeader(b64 string) (string, error)

DecodeCertFromHeader 从 Base64 字符串解码为 PEM 格式证书(用于 HTTP Header). b64: Base64 编码的证书字符串. 返回 PEM 格式证书字符串.

func DecryptWithKey

func DecryptWithKey(keyPEM string, ciphertext []byte) ([]byte, error)

DecryptWithKey 使用私钥解密数据(混合解密). keyPEM: 私钥 PEM 格式字符串. ciphertext: 待解密的密文. 返回解密后的明文.

func EncodeCertForHeader

func EncodeCertForHeader(certPEM string) string

EncodeCertForHeader 将 PEM 格式证书编码为 Base64 字符串(用于 HTTP Header). certPEM: 证书 PEM 格式字符串. 返回 Base64 编码的字符串.

func EncryptWithCert

func EncryptWithCert(certPEM string, plaintext []byte) (ciphertext []byte, nonce []byte, err error)

EncryptWithCert 使用证书公钥加密数据(混合加密). 支持 RSA/ECDSA/Ed25519 证书. certPEM: 证书 PEM 格式字符串(仅需公钥). plaintext: 待加密的明文. 返回加密后的数据和 nonce.

func ExtractPublicKeyFromCert

func ExtractPublicKeyFromCert(certStr string) (string, error)

ExtractPublicKeyFromCert 从证书中提取公钥.

func GenCACert

func GenCACert(cfg *CACertConfig) error

GenCACert 根据配置生成自签名 CA 证书与私钥.

func GenerateCASignedCert

func GenerateCASignedCert(cfg *CASignedCertConfig) error

GenerateCASignedCert 根据配置生成由 CA 签发的证书与私钥.

func GenerateCRL

func GenerateCRL(cfg *CRLConfig) error

GenerateCRL 根据配置生成证书吊销列表(CRL).

func GenerateCSR

func GenerateCSR(cfg *CSRConfig) error

GenerateCSR 生成证书签名请求(CSR).

func GenerateIntermediateCA

func GenerateIntermediateCA(cfg *CASignedCertConfig) error

GenerateIntermediateCA 生成由上级 CA 签发的中间 CA 证书与私钥.

func GetCertFingerprint

func GetCertFingerprint(certPEM string, hashAlgo string) (string, error)

GetCertFingerprint 计算证书指纹. certPEM: 证书 PEM 格式字符串. hashAlgo: 哈希算法, 支持 "sha256", "sha384", "sha512". 返回格式为 "算法:十六进制指纹" 的字符串, 例如 "sha256:abc123...".

func IsCertRevoked

func IsCertRevoked(certPEM, crlPEM string) (bool, error)

IsCertRevoked 检查证书是否被吊销.

  • certPEM: 待检查的证书 PEM 字符串.
  • crlPEM: CRL PEM 字符串.

func MarshalECPrivateKeyToSEC1

func MarshalECPrivateKeyToSEC1(keyStr string) (string, error)

MarshalECPrivateKeyToSEC1 将 ECDSA 私钥编码为 SEC 1 格式.

func MarshalPrivateKeyToPKCS1

func MarshalPrivateKeyToPKCS1(keyStr string) (string, error)

MarshalPrivateKeyToPKCS1 将 RSA 私钥编码为 PKCS#1 格式(兼容旧格式).

func ParseCertificate

func ParseCertificate(certPEM string) (*x509.Certificate, error)

ParseCertificate 解析 PEM 格式证书.

func ParsePrivateKey

func ParsePrivateKey(keyStr string) (crypto.Signer, error)

ParsePrivateKey 解析 PEM 格式私钥(支持 PKCS#8, PKCS#1, SEC 1). nolint:gocognit

func SignCSR

func SignCSR(cfg *CSRSignConfig) error

SignCSR 使用 CA 签发 CSR.

func SignData

func SignData(keyPEM string, data []byte) ([]byte, error)

SignData 使用私钥对数据进行签名. keyPEM: 私钥 PEM 格式字符串. data: 待签名的数据. 返回签名结果.

func ValidateCACertConfig

func ValidateCACertConfig(cfg *CACertConfig) error

ValidateCACertConfig 验证 CA 证书配置.

func ValidateCASignedCertConfig

func ValidateCASignedCertConfig(cfg *CASignedCertConfig) error

ValidateCASignedCertConfig 验证 CA 签发证书配置.

func ValidateCRLConfig

func ValidateCRLConfig(cfg *CRLConfig) error

ValidateCRLConfig 验证 CRL 配置.

func ValidateCSRConfig

func ValidateCSRConfig(cfg *CSRConfig) error

ValidateCSRConfig 验证 CSR 配置.

func ValidateCSRSignConfig

func ValidateCSRSignConfig(cfg *CSRSignConfig) error

ValidateCSRSignConfig 验证 CSR 签发配置.

func ValidateCert

func ValidateCert(cfg *CertValidateConfig) error

ValidateCert 验证证书的有效性.

func VerifySignature

func VerifySignature(certPEM string, data, signature []byte) error

VerifySignature 使用证书公钥验证签名. certPEM: 证书 PEM 格式字符串. data: 原始数据. signature: 签名. 返回 nil 表示验证成功, 否则返回错误.

Types

type CACertConfig

type CACertConfig struct {
	RSAKeyBits   int          // [RSA] 私钥位数(默认2048, 可选4096)
	DaysValid    int          // 证书有效期(天)
	Subject      Subject      // 证书主题信息
	Key          string       // 私钥
	Cert         string       // 证书
	KeyAlgorithm KeyAlgorithm // 密钥算法(RSA/ECDSA/Ed25519)
	ECDSACurve   ECDSACurve   // [ECDSA] 曲线(P256/P384/P521)
	PathLenZero  bool         // 是否为终端 CA(不能签发下级 CA)
	MaxPathLen   int          // 最大路径长度(-1 表示无限制), 用于限制下级 CA 签发能力
}

CACertConfig CA 证书生成参数.

type CASignedCertConfig

type CASignedCertConfig struct {
	CACert       string       // CA 证书
	CAKey        string       // CA 私钥
	Name         string       // 证书名称
	Subject      Subject      // 证书主题
	Cert         string       // 证书
	Key          string       // 私钥
	DaysValid    int          // 证书有效期(天)
	RSAKeyBits   int          // [RSA] 私钥位数(默认2048, 可选4096)
	KeyAlgorithm KeyAlgorithm // 密钥算法(RSA/ECDSA/Ed25519)
	ECDSACurve   ECDSACurve   // [ECDSA] 曲线(P256/P384/P521)
	SAN          SANConfig    // 主题备用名称
	Usage        CertUsage    // 证书用途(服务器/客户端等)
	IsCA         bool         // 是否为中间 CA
	MaxPathLen   int          // 中间 CA 最大路径长度
}

CASignedCertConfig 由 CA 签发的证书配置.

type CRLConfig

type CRLConfig struct {
	CACert         string     // CA 证书
	CAKey          string     // CA 私钥
	RevokedCerts   []string   // 要吊销的证书列表(PEM 格式)
	ExistingCRL    string     // 现有的 CRL(PEM 格式), 新吊销会合并进去
	SkipExpired    bool       // 跳过已过期的证书(不吊销已过期的证书)
	PruneAfterDays int        // 剔除吊销超过 N 天的历史记录(0 表示不剔除)
	DaysValid      int        // CRL 有效期(天)
	CRL            string     // 生成的 CRL(PEM 格式)
	ThisUpdate     time.Time  // 本次更新时间
	NextUpdate     time.Time  // 下次更新时间
	RevokedSerials []*big.Int // 已吊销证书序列号列表
	SkippedExpired int        // 跳过的已过期证书数量(输出)
	PrunedCount    int        // 剔除的历史记录数量(输出)
}

CRLConfig 证书吊销列表配置.

type CSRConfig

type CSRConfig struct {
	Subject      Subject      // 证书主题
	RSAKeyBits   int          // [RSA] 私钥位数(默认2048)
	KeyAlgorithm KeyAlgorithm // 密钥算法(RSA/ECDSA/Ed25519)
	ECDSACurve   ECDSACurve   // [ECDSA] 曲线(P256/P384/P521)
	SAN          SANConfig    // 主题备用名称
	CSR          string       // 生成的 CSR(PEM 格式)
	Key          string       // 生成的私钥(PEM 格式)
}

CSRConfig 证书签名请求配置.

type CSRSignConfig

type CSRSignConfig struct {
	CACert    string    // CA 证书
	CAKey     string    // CA 私钥
	CSR       string    // 待签发的 CSR
	DaysValid int       // 证书有效期(天)
	Usage     CertUsage // 证书用途
	IsCA      bool      // 是否为 CA 证书
	Cert      string    // 签发的证书
}

CSRSignConfig CSR 签发配置.

type CertChainConfig

type CertChainConfig struct {
	EndEntityCert   string   // 终端实体证书
	IntermediateCAs []string // 中间 CA 证书列表(从低到高排序)
	RootCA          string   // 根 CA 证书
	FullChain       string   // 完整证书链(PEM 格式)
}

CertChainConfig 证书链配置.

type CertInfo

type CertInfo struct {
	SerialNumber string    // 证书序列号
	Subject      string    // 证书主题
	Issuer       string    // 证书颁发者
	NotBefore    time.Time // 生效时间
	NotAfter     time.Time // 过期时间
	IsCA         bool      // 是否为 CA 证书
	KeyAlgorithm string    // 密钥算法
	DNSNames     []string  // DNS 名称列表
	IPAddresses  []string  // IP 地址列表
	ExtKeyUsages []string  // 扩展密钥用途
}

CertInfo 证书信息结构.

func GetCertInfo

func GetCertInfo(certPEM string) (*CertInfo, error)

GetCertInfo 通过证书 PEM 字符串获取证书信息.

type CertUsage

type CertUsage int

CertUsage 证书用途.

const (
	// UsageServer 服务器认证.
	UsageServer CertUsage = 1 << iota
	// UsageClient 客户端认证.
	UsageClient
	// UsageCodeSigning 代码签名.
	UsageCodeSigning
	// UsageEmailProtection 邮件保护.
	UsageEmailProtection
)

type CertValidateConfig

type CertValidateConfig struct {
	Cert            string    // 待验证的证书
	CACert          string    // CA 证书(可选, 用于验证签名)
	IntermediateCAs []string  // 中间 CA 证书链
	CheckTime       time.Time // 验证时间点(零值表示当前时间)
	DNSName         string    // 验证 DNS 名称
	Usage           CertUsage // 验证用途
}

CertValidateConfig 证书验证配置.

type Certificate

type Certificate struct {
	CertPEM      string       // 证书 PEM 格式
	KeyPEM       string       // 私钥 PEM 格式
	KeyAlgorithm KeyAlgorithm // 密钥算法
	// contains filtered or unexported fields
}

Certificate 表示一个证书及其私钥的组合. 根据不同的密钥算法, 支持不同的加密和签名操作.

func NewCertificate

func NewCertificate(certPEM, keyPEM string) (*Certificate, error)

NewCertificate 从 PEM 格式的证书和私钥创建 Certificate 对象.

func NewCertificateFromCert

func NewCertificateFromCert(certPEM string) (*Certificate, error)

NewCertificateFromCert 从已有的证书对象创建 Certificate(仅公钥, 无私钥).

func (*Certificate) GetCryptoOperator

func (c *Certificate) GetCryptoOperator() (CryptoOperator, error)

GetCryptoOperator 根据密钥算法返回对应的加密操作器.

func (*Certificate) GetParsedCert

func (c *Certificate) GetParsedCert() *x509.Certificate

GetParsedCert 获取解析后的 x509.Certificate.

func (*Certificate) GetPrivateKey

func (c *Certificate) GetPrivateKey() crypto.Signer

GetPrivateKey 获取解析后的私钥.

func (*Certificate) HasPrivateKey

func (c *Certificate) HasPrivateKey() bool

HasPrivateKey 检查是否包含私钥.

type CryptoOperator

type CryptoOperator interface {
	// Sign 使用私钥对数据进行签名.
	Sign(data []byte) ([]byte, error)

	// Verify 使用证书公钥验证签名.
	Verify(data []byte, signature []byte) error

	// HybridEncrypt 混合加密: 结合对称加密和非对称加密.
	// RSA: 使用 RSA 加密 AES 密钥, AES 加密数据.
	// ECDSA/Ed25519: 使用 ECDH 密钥交换派生共享密钥, AES 加密数据.
	// 返回密文和 nonce, 如果 plaintext 为 nil, 则返回 nil 密文和有效的 nonce.
	HybridEncrypt(plaintext []byte) ([]byte, []byte, error)

	// HybridDecrypt 混合解密.
	HybridDecrypt(encryptedPackage []byte) ([]byte, error)

	// GetKeyAlgorithm 获取密钥算法.
	GetKeyAlgorithm() KeyAlgorithm

	// GetCertificate 获取底层证书.
	GetCertificate() *Certificate
}

CryptoOperator 定义证书加密操作接口. 不同类型的证书(RSA/ECDSA/Ed25519)实现此接口.

type ECDSACryptoOperator

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

ECDSACryptoOperator ECDSA 证书加密操作器.

func (*ECDSACryptoOperator) GetCertificate

func (e *ECDSACryptoOperator) GetCertificate() *Certificate

GetCertificate 获取底层证书.

func (*ECDSACryptoOperator) GetKeyAlgorithm

func (e *ECDSACryptoOperator) GetKeyAlgorithm() KeyAlgorithm

GetKeyAlgorithm 获取密钥算法.

func (*ECDSACryptoOperator) HybridDecrypt

func (e *ECDSACryptoOperator) HybridDecrypt(encryptedPackage []byte) ([]byte, error)

HybridDecrypt 混合解密.

func (*ECDSACryptoOperator) HybridEncrypt

func (e *ECDSACryptoOperator) HybridEncrypt(plaintext []byte) ([]byte, []byte, error)

HybridEncrypt 混合加密, 使用 ECDH 密钥交换派生共享密钥, AES 加密数据. 返回密文和 nonce, 如果 plaintext 为 nil, 则返回 nil 密文和有效的 nonce.

func (*ECDSACryptoOperator) Sign

func (e *ECDSACryptoOperator) Sign(data []byte) ([]byte, error)

Sign 使用 ECDSA 私钥对数据进行签名.

func (*ECDSACryptoOperator) Verify

func (e *ECDSACryptoOperator) Verify(data []byte, signature []byte) error

Verify 使用 ECDSA 公钥验证签名.

type ECDSACurve

type ECDSACurve string

ECDSACurve ECDSA 曲线类型.

const (
	CurveP256 ECDSACurve = "P256"
	CurveP384 ECDSACurve = "P384"
	CurveP521 ECDSACurve = "P521"
)

ECDSACurve 枚举值.

type Ed25519CryptoOperator

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

Ed25519CryptoOperator Ed25519 证书加密操作器.

func (*Ed25519CryptoOperator) GetCertificate

func (e *Ed25519CryptoOperator) GetCertificate() *Certificate

GetCertificate 获取底层证书.

func (*Ed25519CryptoOperator) GetKeyAlgorithm

func (e *Ed25519CryptoOperator) GetKeyAlgorithm() KeyAlgorithm

GetKeyAlgorithm 获取密钥算法.

func (*Ed25519CryptoOperator) HybridDecrypt

func (e *Ed25519CryptoOperator) HybridDecrypt(encryptedPackage []byte) ([]byte, error)

HybridDecrypt 混合解密.

func (*Ed25519CryptoOperator) HybridEncrypt

func (e *Ed25519CryptoOperator) HybridEncrypt(plaintext []byte) ([]byte, []byte, error)

HybridEncrypt 混合加密: 使用 X25519 ECDH 密钥交换派生共享密钥, AES 加密数据. Ed25519 公钥会被转换为 X25519 公钥用于密钥交换. 返回密文和 nonce, 如果 plaintext 为 nil, 则返回 nil 密文和有效的 nonce.

func (*Ed25519CryptoOperator) Sign

func (e *Ed25519CryptoOperator) Sign(data []byte) ([]byte, error)

Sign 使用 Ed25519 私钥对数据进行签名.

func (*Ed25519CryptoOperator) Verify

func (e *Ed25519CryptoOperator) Verify(data []byte, signature []byte) error

Verify 使用 Ed25519 公钥验证签名.

type KeyAlgorithm

type KeyAlgorithm string

KeyAlgorithm 密钥算法类型.

const (
	KeyAlgorithmRSA     KeyAlgorithm = "RSA"
	KeyAlgorithmECDSA   KeyAlgorithm = "ECDSA"
	KeyAlgorithmEd25519 KeyAlgorithm = "Ed25519"
)

KeyAlgorithm 枚举值.

type PEMBlockType

type PEMBlockType string

PEMBlockType PEM 块类型.

const (
	PEMBlockCertificate        PEMBlockType = "CERTIFICATE"         // X.509 证书.
	PEMBlockPrivateKey         PEMBlockType = "PRIVATE KEY"         // PKCS#8 私钥.
	PEMBlockRSAPrivateKey      PEMBlockType = "RSA PRIVATE KEY"     // PKCS#1 RSA 私钥.
	PEMBlockECPrivateKey       PEMBlockType = "EC PRIVATE KEY"      // SEC 1 EC 私钥.
	PEMBlockPublicKey          PEMBlockType = "PUBLIC KEY"          // PKIX 公钥.
	PEMBlockCertificateRequest PEMBlockType = "CERTIFICATE REQUEST" // 证书签名请求.
	PEMBlockCRL                PEMBlockType = "X509 CRL"            // 证书吊销列表.
)

PEMBlockType 枚举值.

type RSACryptoOperator

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

RSACryptoOperator RSA 证书加密操作器.

func (*RSACryptoOperator) GetCertificate

func (r *RSACryptoOperator) GetCertificate() *Certificate

GetCertificate 获取底层证书.

func (*RSACryptoOperator) GetKeyAlgorithm

func (r *RSACryptoOperator) GetKeyAlgorithm() KeyAlgorithm

GetKeyAlgorithm 获取密钥算法.

func (*RSACryptoOperator) HybridDecrypt

func (r *RSACryptoOperator) HybridDecrypt(encryptedPackage []byte) ([]byte, error)

HybridDecrypt 混合解密.

func (*RSACryptoOperator) HybridEncrypt

func (r *RSACryptoOperator) HybridEncrypt(plaintext []byte) ([]byte, []byte, error)

HybridEncrypt 混合加密: 使用 AES 加密数据, 使用 RSA 加密 AES 密钥. 返回密文和 nonce, 如果 plaintext 为 nil, 则返回 nil 密文和有效的 nonce.

func (*RSACryptoOperator) Sign

func (r *RSACryptoOperator) Sign(data []byte) ([]byte, error)

Sign 使用 RSA 私钥对数据进行签名(PKCS1v15 with SHA-256).

func (*RSACryptoOperator) Verify

func (r *RSACryptoOperator) Verify(data []byte, signature []byte) error

Verify 使用 RSA 公钥验证签名(PKCS1v15 with SHA-256).

type RevokedCertInfo

type RevokedCertInfo struct {
	SerialNumber   *big.Int  // 证书序列号
	RevocationTime time.Time // 吊销时间
	Reason         int       // 吊销原因
}

RevokedCertInfo 吊销证书信息.

func ParseCRL

func ParseCRL(crlPEM string) ([]RevokedCertInfo, error)

ParseCRL 解析 CRL 并返回已吊销证书信息.

type SANConfig

type SANConfig struct {
	DNSNames    []string // DNS 名称列表
	IPAddresses []net.IP // IP 地址列表
	EmailAddrs  []string // 电子邮件地址列表
	URIs        []string // URI 列表
}

SANConfig 主题备用名称配置.

func ParseSANFromStr

func ParseSANFromStr(dnsNames, ipAddrs string) SANConfig

ParseSANFromStr 从逗号分隔的字符串解析 SAN 配置.

type Subject

type Subject struct {
	Country            string // 国家
	State              string // 省份
	Locality           string // 城市
	Organization       string // 组织
	OrganizationalUnit string // 组织单位
	CommonName         string // 通用名称
}

Subject 描述 X.509 证书主题字段.

Jump to

Keyboard shortcuts

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