tls

package
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Jul 20, 2026 License: MIT Imports: 15 Imported by: 0

README

web/tls 包 — TLS 配置与加解密工具

所属层级: Infrastructure Layer
设计理念: 安全通信,加密支持

概述

web/tls 包位于 Infrastructure Layer,提供 HTTPS 客户端构建、TLS 证书管理以及通用加解密工具。

核心功能
功能 说明
HTTPS 客户端 基于 net.NetClient 封装,支持 TLS 配置、超时、默认请求头
AES 加解密 CBC 模式(带 PKCS7 填充)和 GCM 模式(推荐,自带认证)
RSA 加解密 OAEP-SHA256 加密/解密
RSA 签名 PKCS1v15-SHA256 签名/验签
TLS 配置 从文件或 PEM 数据加载证书,支持 CA 验证
PEM 编解码 密钥的 PEM 格式序列化与反序列化

HTTPS 客户端

NewClient — 创建 HTTPS 客户端
func NewClient(baseURL string, opts ...ClientOption) *net.NetClient
client := https.NewClient("https://api.example.com",
    https.WithTimeout(30*time.Second),
    https.WithDefaultHeader("Authorization", "Bearer token123"),
)
resp, err := client.Get(ctx, "/api/users")
ClientOption
选项 说明
WithTLSConfig(tlsConfig) 设置 TLS 配置
WithInsecureTLS() 跳过证书验证(仅开发测试)
WithTimeout(timeout) 设置请求超时时间
WithDefaultHeader(key, value) 设置默认请求头
WithTransport(transport) 设置自定义 HTTP Transport
WithTLSConfig
tlsCfg, _ := https.LoadTLSConfig("server.crt", "server.key")
client := https.NewClient("https://example.com",
    https.WithTLSConfig(tlsCfg),
)
WithInsecureTLS
// 仅用于开发测试,跳过证书验证
client := https.NewClient("https://localhost:8443",
    https.WithInsecureTLS(),
)
WithTimeout
client := https.NewClient("https://api.example.com",
    https.WithTimeout(10*time.Second),
)
WithDefaultHeader
client := https.NewClient("https://api.example.com",
    https.WithDefaultHeader("Authorization", "Bearer eyJhbGciOiJ..."),
    https.WithDefaultHeader("X-Request-Id", "uuid-123"),
)
WithTransport
transport := &http.Transport{
    MaxIdleConns:    50,
    IdleConnTimeout: 60 * time.Second,
}
client := https.NewClient("https://api.example.com",
    https.WithTransport(transport),
)
完整使用示例
package main

import (
    "context"
    "fmt"
    "log"
    "time"
    "github.com/xudefa/enhance/https"
)

type User struct {
    ID   int    `json:"id"`
    Name string `json:"name"`
}

func main() {
    client := https.NewClient("https://jsonplaceholder.typicode.com",
        https.WithTimeout(10*time.Second),
    )

    ctx := context.Background()

    // GET 请求
    resp, err := client.Get(ctx, "/users/1")
    if err != nil {
        log.Fatal(err)
    }

    if resp.IsSuccess() {
        var user User
        resp.Bind(&user)
        fmt.Printf("用户: %+v\n", user)
    }

    // POST 请求
    newUser := map[string]any{"name": "张三"}
    resp, err = client.Post(ctx, "/users", newUser)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("创建成功:", resp.String())
}

TLS 配置

LoadTLSConfig — 从文件加载 TLS 配置
func LoadTLSConfig(certFile, keyFile string) (*tls.Config, error)
tlsCfg, err := https.LoadTLSConfig("server.crt", "server.key")
if err != nil {
    log.Fatal(err)
}
LoadTLSConfigWithCA — 加载 TLS 配置并启用 CA 验证
func LoadTLSConfigWithCA(certFile, keyFile, caFile string) (*tls.Config, error)
tlsCfg, err := https.LoadTLSConfigWithCA("client.crt", "client.key", "ca.crt")
if err != nil {
    log.Fatal(err)
}
LoadClientTLSConfig — 仅客户端验证(无需客户端证书)
func LoadClientTLSConfig(caFile string) (*tls.Config, error)
tlsCfg, err := https.LoadClientTLSConfig("ca.crt")
if err != nil {
    log.Fatal(err)
}
// 验证服务端证书,但不需要客户端证书
LoadCertFromPEM — 从 PEM 字节数据加载
func LoadCertFromPEM(certPEM, keyPEM []byte) (*tls.Config, error)
certPEM := []byte("-----BEGIN CERTIFICATE-----\n...")
keyPEM := []byte("-----BEGIN RSA PRIVATE KEY-----\n...")
tlsCfg, err := https.LoadCertFromPEM(certPEM, keyPEM)
InsecureTLSConfig — 跳过证书验证
func InsecureTLSConfig() *tls.Config
cfg := https.InsecureTLSConfig()
// cfg.InsecureSkipVerify = true, MinVersion = tls.VersionTLS12
MustLoadTLSConfig — 失败时 panic
func MustLoadTLSConfig(certFile, keyFile string) *tls.Config
cfg := https.MustLoadTLSConfig("server.crt", "server.key")
// 加载失败直接 panic,适用于初始化阶段

AES 加解密

AESEncrypt / AESDecrypt — CBC 模式(带 PKCS7 填充)
func AESEncrypt(plaintext, key, iv []byte) ([]byte, error)
func AESDecrypt(ciphertext, key, iv []byte) ([]byte, error)
  • key:16/24/32 字节,对应 AES-128/AES-192/AES-256
  • iv:16 字节初始向量
key := []byte("1234567890123456")  // AES-128
iv := []byte("1234567890123456")   // 16 字节

plaintext := []byte("Hello, World!")

ciphertext, err := https.AESEncrypt(plaintext, key, iv)
if err != nil {
    log.Fatal(err)
}

decrypted, err := https.AESDecrypt(ciphertext, key, iv)
if err != nil {
    log.Fatal(err)
}
fmt.Println(string(decrypted)) // "Hello, World!"
AESGCMEncrypt / AESGCMDecrypt — GCM 模式(推荐)
func AESGCMEncrypt(plaintext, key, additionalData []byte) ([]byte, error)
func AESGCMDecrypt(ciphertext, key, additionalData []byte) ([]byte, error)
  • GCM 模式自带认证标签,能检测密文篡改
  • 输出格式:nonce + ciphertext + tag(nonce 为随机生成 12 字节)
  • additionalData 为可选的附加认证数据
key := []byte("1234567890123456") // AES-128

plaintext := []byte("Hello, World!")

// 加密
ciphertext, err := https.AESGCMEncrypt(plaintext, key, nil)
if err != nil {
    log.Fatal(err)
}

// 解密
decrypted, err := https.AESGCMDecrypt(ciphertext, key, nil)
if err != nil {
    log.Fatal(err)
}
fmt.Println(string(decrypted)) // "Hello, World!"

// 带附加认证数据
aad := []byte("additional-data")
ciphertext, _ = https.AESGCMEncrypt(plaintext, key, aad)
decrypted, _ = https.AESGCMDecrypt(ciphertext, key, aad)

RSA 加解密

RSAGenerateKey — 生成密钥对
func RSAGenerateKey(bits int) (*rsa.PrivateKey, error)
privateKey, err := https.RSAGenerateKey(2048)
if err != nil {
    log.Fatal(err)
}
publicKey := &privateKey.PublicKey
RSAEncrypt / RSADecrypt — OAEP-SHA256
func RSAEncrypt(publicKey *rsa.PublicKey, plaintext []byte) ([]byte, error)
func RSADecrypt(privateKey *rsa.PrivateKey, ciphertext []byte) ([]byte, error)
privateKey, _ := https.RSAGenerateKey(2048)
publicKey := &privateKey.PublicKey

plaintext := []byte("Hello, RSA!")
ciphertext, err := https.RSAEncrypt(publicKey, plaintext)
if err != nil {
    log.Fatal(err)
}

decrypted, err := https.RSADecrypt(privateKey, ciphertext)
if err != nil {
    log.Fatal(err)
}
fmt.Println(string(decrypted)) // "Hello, RSA!"

RSA 签名与验签

RSASign / RSAVerify — PKCS1v15-SHA256
func RSASign(privateKey *rsa.PrivateKey, data []byte) ([]byte, error)
func RSAVerify(publicKey *rsa.PublicKey, data, signature []byte) error
privateKey, _ := https.RSAGenerateKey(2048)
publicKey := &privateKey.PublicKey

data := []byte("待签名的数据")

// 签名
signature, err := https.RSASign(privateKey, data)
if err != nil {
    log.Fatal(err)
}

// 验签
err = https.RSAVerify(publicKey, data, signature)
if err != nil {
    log.Fatal("签名验证失败")
} else {
    fmt.Println("签名验证通过")
}

PEM 编解码

编码
func MarshalRSAPrivateKey(privateKey *rsa.PrivateKey) []byte
func MarshalRSAPublicKey(publicKey *rsa.PublicKey) ([]byte, error)
privateKey, _ := https.RSAGenerateKey(2048)

// 私钥 -> PEM
privPEM := https.MarshalRSAPrivateKey(privateKey)
os.WriteFile("private.pem", privPEM, 0600)

// 公钥 -> PEM
pubPEM, _ := https.MarshalRSAPublicKey(&privateKey.PublicKey)
os.WriteFile("public.pem", pubPEM, 0644)
解码
func ParseRSAPrivateKey(pemData []byte) (*rsa.PrivateKey, error)
func ParseRSAPublicKey(pemData []byte) (*rsa.PublicKey, error)
// 从 PEM 文件读取
pemData, _ := os.ReadFile("private.pem")
privateKey, err := https.ParseRSAPrivateKey(pemData)
if err != nil {
    log.Fatal(err)
}

pemData, _ = os.ReadFile("public.pem")
publicKey, err := https.ParseRSAPublicKey(pemData)
if err != nil {
    log.Fatal(err)
}

完整 API 参考

函数/类型 说明
NewClient(baseURL, opts...) 创建 HTTPS 客户端
WithTLSConfig(cfg) 设置 TLS 配置
WithInsecureTLS() 跳过证书验证
WithTimeout(timeout) 设置超时
WithDefaultHeader(k, v) 设置默认请求头
WithTransport(t) 设置自定义 Transport
LoadTLSConfig(certFile, keyFile) 从文件加载 TLS 配置
LoadTLSConfigWithCA(cert, key, ca) 加载 TLS + CA 验证
LoadClientTLSConfig(caFile) 加载客户端 TLS 配置
LoadCertFromPEM(certPEM, keyPEM) 从 PEM 字节加载
InsecureTLSConfig() 创建不安全 TLS 配置
MustLoadTLSConfig(cert, key) 加载 TLS 配置(失败 panic)
AESEncrypt(plain, key, iv) AES-CBC 加密
AESDecrypt(cipher, key, iv) AES-CBC 解密
AESGCMEncrypt(plain, key, aad) AES-GCM 加密(推荐)
AESGCMDecrypt(cipher, key, aad) AES-GCM 解密
RSAGenerateKey(bits) 生成 RSA 密钥对
RSAEncrypt(pub, plain) RSA OAEP 加密
RSADecrypt(priv, cipher) RSA OAEP 解密
RSASign(priv, data) RSA PKCS1v15 签名
RSAVerify(pub, data, sig) RSA 验签
MarshalRSAPrivateKey(key) RSA 私钥→PEM
MarshalRSAPublicKey(key) RSA 公钥→PEM
ParseRSAPrivateKey(pem) PEM→RSA 私钥
ParseRSAPublicKey(pem) PEM→RSA 公钥

Documentation

Overview

Package tls 提供 TLS 证书管理和加密工具,用于 enhance 框架。

该模块提供 TLS 配置、HTTPS 客户端、AES/RSA 加密解密等安全通信和加密功能。 适用于需要安全通信和数据加密的场景。

架构设计

  • TLSConfig: TLS 配置管理器,负责证书和密钥管理
  • HTTPSServer: HTTPS 服务器,支持 TLS 通信
  • AESCipher: AES 加密解密器
  • RSACipher: RSA 加密解密器
  • CertificateManager: 证书管理器

核心功能

  • TLS 配置: 支持 TLS 1.2/1.3 协议配置
  • 证书管理: 支持证书加载、验证、更新
  • AES 加密: 支持 AES-128/256 对称加密
  • RSA 加密: 支持 RSA 非对称加密
  • HTTPS 客户端: 支持 HTTPS 请求,验证服务器证书

使用方式

TLS 配置:

cfg := tls.NewTLSConfig()
cfg.SetCertificate("/path/to/cert.pem", "/path/to/key.pem")
cfg.SetMinVersion(tls.VersionTLS12)

AES 加密:

cipher := tls.NewAESCipher(key)
encrypted, err := cipher.Encrypt(plaintext)
decrypted, err := cipher.Decrypt(encrypted)

RSA 加密:

cipher := tls.NewRSACipher(publicKey)
encrypted, err := cipher.Encrypt(plaintext)

支持的加密算法

  • AES-128-CBC: AES 128 位 CBC 模式
  • AES-256-CBC: AES 256 位 CBC 模式
  • AES-128-GCM: AES 128 位 GCM 模式
  • AES-256-GCM: AES 256 位 GCM 模式
  • RSA-2048: RSA 2048 位密钥
  • RSA-4096: RSA 4096 位密钥

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AESDecrypt

func AESDecrypt(ciphertext, key, iv []byte) ([]byte, error)

AESDecrypt 使用 AES-CBC 模式解密数据。

参数:

  • ciphertext: 密文数据
  • key: 密钥(需与加密时一致)
  • iv: 初始向量(需与加密时一致)

返回值:

  • []byte: 明文数据
  • error: 解密错误

func AESEncrypt

func AESEncrypt(plaintext, key, iv []byte) ([]byte, error)

AESEncrypt 使用 AES-CBC 模式加密数据。

参数:

  • plaintext: 明文数据
  • key: 密钥(16/24/32 字节对应 AES-128/AES-192/AES-256)
  • iv: 初始向量(16 字节)

返回值:

  • []byte: 密文数据
  • error: 加密错误

func AESGCMDecrypt

func AESGCMDecrypt(ciphertext, key, additionalData []byte) ([]byte, error)

AESGCMDecrypt 使用 AES-GCM 模式解密数据。

参数:

  • ciphertext: nonce + 密文 + tag(AESGCMEncrypt 的输出格式)
  • key: 密钥(需与加密时一致)
  • additionalData: 附加认证数据(需与加密时一致)

返回值:

  • []byte: 明文数据
  • error: 解密错误

func AESGCMEncrypt

func AESGCMEncrypt(plaintext, key, additionalData []byte) ([]byte, error)

AESGCMEncrypt 使用 AES-GCM 模式加密数据(推荐,自带认证)。

参数:

  • plaintext: 明文数据
  • key: 密钥(16/24/32 字节)
  • additionalData: 附加认证数据(可选)

返回值:

  • []byte: nonce + 密文 + tag(拼接格式)
  • error: 加密错误

func InsecureTLSConfig

func InsecureTLSConfig() *tls.Config

InsecureTLSConfig 创建跳过证书验证的 TLS 配置(仅用于开发测试)。

返回值:

  • *tls.Config: 不安全但可用的 TLS 配置

func LoadCertFromPEM

func LoadCertFromPEM(certPEM, keyPEM []byte) (*tls.Config, error)

LoadCertFromPEM 从 PEM 编码的字节数据解析 TLS 证书对。

参数:

  • certPEM: PEM 格式的证书数据
  • keyPEM: PEM 格式的私钥数据

返回值:

  • *tls.Config: TLS 配置
  • error: 解析错误

func LoadClientTLSConfig

func LoadClientTLSConfig(caFile string) (*tls.Config, error)

LoadClientTLSConfig 加载仅客户端验证用的 TLS 配置(不需要服务端证书)。

参数:

  • caFile: PEM 格式的 CA 证书文件路径,用于验证服务端证书

返回值:

  • *tls.Config: TLS 配置
  • error: 加载错误

func LoadTLSConfig

func LoadTLSConfig(certFile, keyFile string) (*tls.Config, error)

LoadTLSConfig 从证书文件和密钥文件加载 TLS 配置。

参数:

  • certFile: PEM 格式的证书文件路径
  • keyFile: PEM 格式的私钥文件路径

返回值:

  • *tls.Config: TLS 配置
  • error: 加载错误

示例:

tlsCfg, err := tls.LoadTLSConfig("server.crt", "server.key")
if err != nil {
    log.Fatal(err)
}

func LoadTLSConfigWithCA

func LoadTLSConfigWithCA(certFile, keyFile, caFile string) (*tls.Config, error)

LoadTLSConfigWithCA 加载 TLS 配置并启用 CA 证书验证(用于客户端验证服务端)。

参数:

  • certFile: PEM 格式的证书文件路径
  • keyFile: PEM 格式的私钥文件路径
  • caFile: PEM 格式的 CA 证书文件路径

返回值:

  • *tls.Config: TLS 配置
  • error: 加载错误

func MarshalRSAPrivateKey

func MarshalRSAPrivateKey(privateKey *rsa.PrivateKey) []byte

MarshalRSAPrivateKey 将 RSA 私钥编码为 PEM 格式。

func MarshalRSAPublicKey

func MarshalRSAPublicKey(publicKey *rsa.PublicKey) ([]byte, error)

MarshalRSAPublicKey 将 RSA 公钥编码为 PEM 格式。

func MustLoadTLSConfig

func MustLoadTLSConfig(certFile, keyFile string) *tls.Config

MustLoadTLSConfig 加载 TLS 配置,失败时 panic。

参数:

  • certFile: PEM 格式的证书文件路径
  • keyFile: PEM 格式的私钥文件路径

返回值:

  • *tls.Config: TLS 配置

func NewClient

func NewClient(baseURL string, opts ...ClientOption) *server.NetClient

NewClient 创建 HTTPS 客户端构建器。

参数:

返回值:

  • *server.NetClient: 配置好的 HTTPS 客户端实例

示例:

client := https.NewClient("https://api.example.com",
    https.WithInsecureTLS(),
    https.WithTimeout(30*time.Second),
)
resp, err := client.Get(ctx, "/api/users")

func ParseRSAPrivateKey

func ParseRSAPrivateKey(pemData []byte) (*rsa.PrivateKey, error)

ParseRSAPrivateKey 从 PEM 数据解析 RSA 私钥。

func ParseRSAPublicKey

func ParseRSAPublicKey(pemData []byte) (*rsa.PublicKey, error)

ParseRSAPublicKey 从 PEM 数据解析 RSA 公钥。

func RSADecrypt

func RSADecrypt(privateKey *rsa.PrivateKey, ciphertext []byte) ([]byte, error)

RSADecrypt 使用 RSA 私钥解密数据(OAEP-SHA256)。

参数:

  • privateKey: RSA 私钥
  • ciphertext: 密文数据

返回值:

  • []byte: 明文数据
  • error: 解密错误

func RSAEncrypt

func RSAEncrypt(publicKey *rsa.PublicKey, plaintext []byte) ([]byte, error)

RSAEncrypt 使用 RSA 公钥加密数据(OAEP-SHA256)。

参数:

  • publicKey: RSA 公钥
  • plaintext: 明文数据

返回值:

  • []byte: 密文数据
  • error: 加密错误

func RSAGenerateKey

func RSAGenerateKey(bits int) (*rsa.PrivateKey, error)

RSAGenerateKey 生成 RSA 密钥对。

参数:

  • bits: 密钥位数(建议 2048 或 4096)

返回值:

  • *rsa.PrivateKey: 私钥
  • error: 生成错误

func RSASign

func RSASign(privateKey *rsa.PrivateKey, data []byte) ([]byte, error)

RSASign 使用 RSA 私钥签名数据(PKCS1v15-SHA256)。

参数:

  • privateKey: RSA 私钥
  • data: 待签名数据

返回值:

  • []byte: 签名
  • error: 签名错误

func RSAVerify

func RSAVerify(publicKey *rsa.PublicKey, data, signature []byte) error

RSAVerify 使用 RSA 公钥验证签名。

参数:

  • publicKey: RSA 公钥
  • data: 原始数据
  • signature: 签名

返回值:

  • error: 验证错误(nil 表示验证通过)

Types

type ClientBuilder

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

ClientBuilder 是 HTTPS 客户端构建器,封装 server.NetClient 并配置 TLS。

字段说明:

  • baseURL: 基础 URL(应以 https:// 开头)
  • tlsConfig: TLS 配置
  • timeout: 请求超时时间
  • transport: 自定义 HTTP Transport
  • headers: 默认请求头

type ClientOption

type ClientOption func(*ClientBuilder)

ClientOption 是 HTTPS 客户端配置选项。

func WithDefaultHeader

func WithDefaultHeader(key, value string) ClientOption

WithDefaultHeader 设置默认请求头。

参数:

  • key: 请求头名称
  • value: 请求头值

返回值:

  • ClientOption: 客户端配置选项

func WithInsecureTLS

func WithInsecureTLS() ClientOption

WithInsecureTLS 跳过 TLS 证书验证(仅用于开发测试)。

返回值:

  • ClientOption: 客户端配置选项

func WithTLSConfig

func WithTLSConfig(tlsConfig *tls.Config) ClientOption

WithTLSConfig 设置 TLS 配置。

参数:

  • tlsConfig: TLS 配置

返回值:

  • ClientOption: 客户端配置选项

func WithTimeout

func WithTimeout(timeout time.Duration) ClientOption

WithTimeout 设置请求超时时间。

参数:

  • timeout: 超时时间

返回值:

  • ClientOption: 客户端配置选项

func WithTransport

func WithTransport(transport *http.Transport) ClientOption

WithTransport 设置自定义 HTTP Transport。

参数:

  • transport: HTTP Transport

返回值:

  • ClientOption: 客户端配置选项

Jump to

Keyboard shortcuts

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