security

package
v0.17.6 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2026 License: MIT Imports: 27 Imported by: 1

README

Security 组件

安全组件提供全面的安全功能,包括数据加密、密码处理、输入过滤和国密算法支持。

概述

Security 组件是一个功能丰富的安全工具库,为 Go 应用程序提供企业级的安全保障。组件包含 AES 加密、SM4 国密算法、密码哈希、输入过滤等多种安全功能。

功能特性

  • AES 加密/解密:支持 CBC 模式的 AES 加密,自动处理密钥长度验证和 PKCS7 填充
  • RSA 签名/验签:SHA256withRSA(RSA2)签名与验签,兼容 PKCS1/PKCS8 与裸 base64 密钥串、文件路径三种来源
  • SM4 国密算法:支持 SM4 对称加密,提供 CBC 和 GCM 两种加密模式
  • 密码处理:基于 bcrypt 的密码哈希和验证功能
  • 输入过滤:智能输入清理,防止 SQL 注入和 XSS 攻击
  • 安全过滤:多层次的字符串清理和类型安全处理
  • 基础加密:提供 PBKDF2 和 HKDF 密钥派生功能

快速开始

安装
go get github.com/jcbowen/jcbaseGo/component/security
AES 加密示例
package main

import (
    "fmt"
    "github.com/jcbowen/jcbaseGo/component/security"
)

func main() {
    // 创建 AES 实例
    aes := security.AES{
        Text: "Hello, World!",
        Key:  "16bytekey12345678", // 16/24/32 字节密钥
        Iv:   "16byteiv12345678",  // 16 字节 IV
    }

    // 加密
    var encrypted string
    err := aes.Encrypt(&encrypted)
    if err != nil {
        panic(err)
    }
    fmt.Println("加密结果:", encrypted)

    // 解密
    var decrypted string
    aes.Text = encrypted
    err = aes.Decrypt(&decrypted)
    if err != nil {
        panic(err)
    }
    fmt.Println("解密结果:", decrypted)
}
SM4 加密示例
package main

import (
    "fmt"
    "github.com/jcbowen/jcbaseGo/component/security"
)

func main() {
    // 创建 SM4 实例
    sm4 := security.SM4{
        Text:     "Hello, SM4!",
        Key:      "16bytekey12345678", // 16 字节密钥
        Iv:       "16byteiv12345678",  // 16 字节 IV
        Mode:     "CBC",               // CBC 或 GCM 模式
        Encoding: "Std",               // 输出编码格式
    }

    // 加密
    var encrypted string
    err := sm4.Encrypt(&encrypted)
    if err != nil {
        panic(err)
    }
    fmt.Println("SM4 加密结果:", encrypted)

    // 解密
    var decrypted string
    sm4.Text = encrypted
    err = sm4.Decrypt(&decrypted)
    if err != nil {
        panic(err)
    }
    fmt.Println("SM4 解密结果:", decrypted)
}
密码处理示例
package main

import (
    "fmt"
    "github.com/jcbowen/jcbaseGo/component/security"
)

func main() {
    password := "mySecurePassword123"

    // 生成密码哈希
    hash, err := security.PasswordHash(password, 12) // cost 参数建议 10-14
    if err != nil {
        panic(err)
    }
    fmt.Println("密码哈希:", hash)

    // 验证密码
    isValid := security.PasswordVerify(password, hash)
    fmt.Println("密码验证结果:", isValid)
}
输入过滤示例
package main

import (
    "fmt"
    "github.com/jcbowen/jcbaseGo/component/security"
)

func main() {
    // 清理字符串输入
    input := security.Input{
        Value:        "<script>alert('xss')</script>SELECT * FROM users",
        DefaultValue: "default value",
    }

    // 通用清理
    sanitized := input.Sanitize()
    fmt.Println("通用清理结果:", sanitized)

    // 特定类型清理
    sanitizedStr := input.SanitizeString(input.Value.(string), []string{"sql", "xss"})
    fmt.Println("SQL+XSS 清理结果:", sanitizedStr)

    // HTML 内容清理
    htmlContent := input.Html()
    fmt.Println("HTML 清理结果:", htmlContent)
}

详细配置

AES 配置

AES 结构体支持以下配置:

type AES struct {
    Text string `json:"text" default:""`                // 待加密/解密的文本
    Key  string `json:"key" default:"jcbase.aes_key__"` // 加密密钥(16/24/32 字节)
    Iv   string `json:"iv" default:"jcbase.aes_iv___"`   // 初始化向量(16 字节)
}
SM4 配置

SM4 结构体支持以下配置:

type SM4 struct {
    Text     string `json:"text" default:""`                // 待加密/解密的文本
    Key      string `json:"key" default:"jcbase.sm4_key__"` // 加密密钥(16 字节)
    Iv       string `json:"iv" default:"jcbase.sm4_iv___"`  // 初始化向量(16 字节)
    Mode     string `json:"mode" default:"CBC"`             // 加密模式:CBC/GCM
    Encoding string `json:"encoding" default:"Std"`         // 编码格式:Std/Raw/RawURL/Hex
}
输入过滤配置

Input 结构体提供灵活的输入清理:

type Input struct {
    Value        interface{} // 输入值
    DefaultValue interface{} // 默认值
}

支持以下清理类型:

  • "badStr":清理潜在有害字符串
  • "htmlEntity":处理 HTML 实体
  • "sql":防止 SQL 注入
  • "xss":防止 XSS 攻击

高级功能

自定义加密配置
package main

import (
    "fmt"
    "github.com/jcbowen/jcbaseGo/component/security"
)

func main() {
    // 自定义加密配置
    config := security.CipherConfig{
        Cipher: "AES-256-CBC",
        AllowedCiphers: map[string][]int{
            "AES-256-CBC": {16, 32},
        },
        KdfHash:              "sha256",
        MacHash:              "sha256",
        AuthKeyInfo:          "MyAppAuth",
        DerivationIterations: 100000,
    }

    data := "敏感数据"
    secret := "mySecretKey"

    // 基于密码的加密
    encrypted, err := security.Encrypt(data, secret, true, config)
    if err != nil {
        panic(err)
    }
    fmt.Println("加密结果:", encrypted)

    // 解密
    decrypted, err := security.Decrypt(encrypted, secret, true, config)
    if err != nil {
        panic(err)
    }
    fmt.Println("解密结果:", decrypted)
}
安全输入验证
package main

import (
    "fmt"
    "github.com/jcbowen/jcbaseGo/component/security"
)

func main() {
    input := security.Input{
        Value: "admin",
        DefaultValue: "guest",
    }

    // 检查值是否在允许列表中
    allowedValues := []string{"admin", "user", "guest"}
    result := input.Belong(allowedValues, false) // strict=false 进行宽松匹配
    fmt.Println("验证结果:", result)

    // 严格匹配
    resultStrict := input.Belong(allowedValues, true) // strict=true 进行严格匹配
    fmt.Println("严格验证结果:", resultStrict)
}

性能优化建议

  1. 密钥管理:对于生产环境,建议使用密钥管理系统而非硬编码密钥
  2. 密码强度:bcrypt 的 cost 参数建议设置为 10-14,平衡安全性和性能
  3. 加密模式:GCM 模式提供认证加密,比 CBC 模式更安全
  4. 输入过滤:根据实际需求选择清理类型,避免不必要的性能开销

安全考虑

  • 组件自动验证密钥和 IV 的长度要求
  • 提供默认的安全配置,防止常见安全漏洞
  • 支持国密算法 SM4,满足国内安全标准
  • 输入过滤功能可有效防止 SQL 注入和 XSS 攻击

故障排除

常见错误
  1. 密钥长度错误:确保 AES 密钥为 16/24/32 字节,SM4 密钥为 16 字节
  2. IV 长度错误:确保 IV 为 16 字节
  3. 填充错误:组件自动处理 PKCS7 填充,无需手动干预
调试建议

启用详细日志记录以排查加密/解密问题:

// 在调试模式下启用详细输出
aes := security.AES{
    Text: "test",
    Key:  "16bytekey12345678",
    Iv:   "16byteiv12345678",
}
// 检查密钥和 IV 长度
fmt.Printf("Key length: %d\n", len(aes.Key))
fmt.Printf("IV length: %d\n", len(aes.Iv))

API 参考

主要结构体
AES

提供 AES 加密/解密功能

字段:

  • Text string - 待加密/解密的文本
  • Key string - 加密密钥(16/24/32 字节)
  • Iv string - 初始化向量(16 字节)

方法:

  • Encrypt(cipherText *string) error - 加密文本
  • Decrypt(plaintext *string) error - 解密文本
SM4

提供 SM4 国密算法加密/解密功能

字段:

  • Text string - 待加密/解密的文本
  • Key string - 加密密钥(16 字节)
  • Iv string - 初始化向量(16 字节)
  • Mode string - 加密模式(CBC/GCM)
  • Encoding string - 编码格式(Std/Raw/RawURL/Hex)

方法:

  • Encrypt(cipherText *string) error - 加密文本
  • Decrypt(plaintext *string) error - 解密文本
  • EncryptCBC(cipherText *string) error - CBC 模式加密
  • DecryptCBC(plaintext *string) error - CBC 模式解密
  • EncryptGCM(cipherText *string) error - GCM 模式加密
  • DecryptGCM(plaintext *string) error - GCM 模式解密
Input

提供输入过滤和验证功能

字段:

  • Value interface{} - 输入值
  • DefaultValue interface{} - 默认值

方法:

  • Sanitize() interface{} - 通用清理
  • SanitizeString(str string, args ...any) string - 字符串清理
  • Belong(allow interface{}, strict bool) interface{} - 值验证
  • Html() string - HTML 内容清理
工具函数
  • PasswordHash(password string, cost int) (string, error) - 密码哈希
  • PasswordVerify(password, hash string) bool - 密码验证
  • Encrypt(data, secret string, passwordBased bool, config CipherConfig) (string, error) - 通用加密
  • Decrypt(data, secret string, passwordBased bool, config CipherConfig) (string, error) - 通用解密
  • RSASign(data, privateKey string, keyFromFile bool) (string, error) - SHA256withRSA 签名,返回 base64 签名值
  • RSAVerify(data, sign, publicKey string, keyFromFile bool) (bool, error) - SHA256withRSA 验签
  • ParseRSAPrivateKey(keyBytes []byte) (*rsa.PrivateKey, error) - 解析私钥(兼容 PKCS1/PKCS8/裸串)
  • ParseRSAPublicKey(keyBytes []byte) (*rsa.PublicKey, error) - 解析公钥(兼容 PKIX/PKCS1/裸串)
  • FormatPrivateKeyPEM(rawKey string) string - 裸私钥串包装为 PKCS1 PEM 文本
  • FormatPublicKeyPEM(rawKey string) string - 裸公钥串包装为 X.509 PEM 文本

贡献指南

欢迎提交 Issue 和 Pull Request 来改进 Security 组件。

许可证

Security 组件遵循 MIT 许可证。

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefaultCipherConfig = CipherConfig{
	Cipher: "AES-128-CBC",
	AllowedCiphers: map[string][]int{
		"AES-128-CBC": {16, 16},
		"AES-192-CBC": {16, 24},
		"AES-256-CBC": {16, 32},
	},
	KdfHash:              "sha256",
	MacHash:              "sha256",
	AuthKeyInfo:          "AuthorizationKey",
	DerivationIterations: 100000,
}

DefaultCipherConfig is the default cipher configuration

Functions

func Decrypt

func Decrypt(data, secret string, passwordBased bool, config CipherConfig) (string, error)

Decrypt decrypts data using a password or a key

func Encrypt

func Encrypt(data, secret string, passwordBased bool, config CipherConfig) (string, error)

Encrypt encrypts data using a password or a key

func FormatPrivateKeyPEM added in v0.16.0

func FormatPrivateKeyPEM(rawKey string) string

FormatPrivateKeyPEM 将裸 base64 私钥串包装为标准 PKCS1 PEM 文本。

参数:

  • rawKey: 不含 PEM 头尾的 base64 私钥串(可含空格,内部会清理)

返回值:

  • string: 标准 PEM 格式私钥文本(每行 64 字符)

示例:

pemText := security.FormatPrivateKeyPEM("MIIEpAIBAAK...")

func FormatPublicKeyPEM added in v0.16.0

func FormatPublicKeyPEM(rawKey string) string

FormatPublicKeyPEM 将裸 base64 公钥串包装为标准 X.509 SubjectPublicKeyInfo PEM 文本。

参数:

  • rawKey: 不含 PEM 头尾的 base64 公钥串(可含空格,内部会清理)

返回值:

  • string: 标准 PEM 格式公钥文本(每行 64 字符)

示例:

pemText := security.FormatPublicKeyPEM("MIIBIjANBgkq...")

func GenerateRandomBytes

func GenerateRandomBytes(length int) ([]byte, error)

GenerateRandomBytes generates random bytes of specified length

func ParseRSAPrivateKey added in v0.16.0

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

ParseRSAPrivateKey 解析私钥字节为 rsa.PrivateKey。

自动兼容:PKCS1 PEM、PKCS8 PEM、裸 base64 串(自动包装为 PKCS1 PEM)。

参数:

  • keyBytes: 私钥内容字节

返回值:

  • *rsa.PrivateKey: 解析后的私钥对象
  • error: 无法识别的格式时返回错误

func ParseRSAPublicKey added in v0.16.0

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

ParseRSAPublicKey 解析公钥字节为 rsa.PublicKey。

自动兼容:X.509 SubjectPublicKeyInfo PEM("PUBLIC KEY")、PKCS1 PEM("RSA PUBLIC KEY")、 裸 base64 串(自动包装为 "PUBLIC KEY" PEM)。

参数:

  • keyBytes: 公钥内容字节

返回值:

  • *rsa.PublicKey: 解析后的公钥对象
  • error: 无法识别的格式时返回错误

func PasswordHash

func PasswordHash(password string, cost int) (string, error)

PasswordHash generates a hash of the password

func PasswordVerify

func PasswordVerify(password, hash string) bool

PasswordVerify validates the password against a given hash

func RSASign added in v0.16.0

func RSASign(data, privateKey string, keyFromFile bool) (string, error)

RSASign 使用 RSA 私钥对待签名内容进行 SHA256withRSA(RSA2)签名。

兼容三种私钥来源:

  1. 裸 base64 私钥串(无 PEM 头尾、无换行),自动按 PKCS1 包装;
  2. 标准 PEM 文本(PKCS1 "RSA PRIVATE KEY" 或 PKCS8 "PRIVATE KEY");
  3. 私钥文件路径(keyFromFile=true 时按文件读取,内容同样支持上述两种格式)。

参数:

  • data: 待签名的原始字符串(如支付平台签名串)
  • privateKey: 私钥字符串或私钥文件路径
  • keyFromFile: true 表示 privateKey 为文件路径

返回值:

  • string: base64 编码后的签名值
  • error: 私钥格式错误或签名失败时返回错误

示例:

sign, err := security.RSASign("待签名内容", "MIIEpAIBAAK...", false)

func RSAVerify added in v0.16.0

func RSAVerify(data, sign, publicKey string, keyFromFile bool) (bool, error)

RSAVerify 使用公钥对签名进行 SHA256withRSA(RSA2)验签。

兼容三种公钥来源:

  1. 裸 base64 公钥串(无 PEM 头尾、无换行),自动按 X.509 SubjectPublicKeyInfo 包装;
  2. 标准 PEM 公钥文本("PUBLIC KEY" 或 "RSA PUBLIC KEY");
  3. 公钥文件路径(keyFromFile=true 时按文件读取)。

参数:

  • data: 被签名的原始内容
  • sign: base64 编码的签名值
  • publicKey: 公钥字符串或公钥文件路径
  • keyFromFile: true 表示 publicKey 为文件路径

返回值:

  • bool: true 验签通过;false 验签不通过
  • error: 公钥格式错误等异常情况(验签不通过不算异常,返回 false,nil)

示例:

ok, err := security.RSAVerify("待验签内容", sign, platformPublicKey, false)

Types

type AES

type AES struct {
	Text string `json:"text" default:""`
	Key  string `json:"key" default:"jcbase.aes_key__"`
	Iv   string `json:"iv" default:"jcbase.aes_iv___"`
}

func (AES) Decrypt

func (a AES) Decrypt(plaintext *string) error

Decrypt decrypts the given cipherText using the provided key and iv

func (AES) Encrypt

func (a AES) Encrypt(cipherText *string) error

Encrypt encrypts the given text using the provided key and iv

type CipherConfig

type CipherConfig struct {
	Cipher               string
	AllowedCiphers       map[string][]int
	KdfHash              string
	MacHash              string
	AuthKeyInfo          string
	DerivationIterations int
}

CipherConfig stores the cipher configuration

type IDCipher added in v0.13.24

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

IDCipher uint64 ID 加解密器。

底层复用 SM4(CBC + 标准 Base64),并在标准 Base64 基础上做 URL-safe 字符替换 (+ → -、/ → _)且保留 = 填充。注意:SM4 自带的 Encoding:"RawURL" 会去掉填充, 若业务需要保留填充,应使用 "Std" 编码并依赖本实现的字符替换。

func NewIDCipher added in v0.13.24

func NewIDCipher(sm4 *SM4) *IDCipher

NewIDCipher 创建 ID 加解密器。 sm4 需预先配置 Mode/Encoding(Key/Iv 可留空,加解密时会应用默认值)。 若需要保留 base64 填充,sm4.Encoding 应使用 "Std"。

func (*IDCipher) DecryptUint64 added in v0.13.24

func (c *IDCipher) DecryptUint64(cipherText string) (uint64, error)

DecryptUint64 解密 URL-safe base64 字符串为 uint64(兼容 URL-safe 与标准 base64 两种字符集)。 解密前将 URL-safe 字符归一化为标准 base64;标准 base64 密文不含 - 和 _,不受影响。

参数:

  • cipherText: 加密后的 ID 字符串

返回值:

  • uint64: 解密后的 ID
  • error: SM4 未配置、解密失败或结果无法解析为 uint64 时返回错误

func (*IDCipher) EncryptUint64 added in v0.13.24

func (c *IDCipher) EncryptUint64(id uint64) (string, error)

EncryptUint64 将 uint64 ID 加密为 URL-safe base64 字符串(保留填充)。

参数:

  • id: 待加密的 ID

返回值:

  • string: 加密后的 URL-safe base64 字符串
  • error: SM4 未配置或加密失败时返回错误

type Input

type Input struct {
	Value        interface{}
	DefaultValue interface{}
}

func (Input) Belong

func (s Input) Belong(allow interface{}, strict bool) interface{}

Belong 检查值是否属于允许列表

func (Input) Html

func (s Input) Html() string

Html 清理并返回HTML内容

func (Input) Sanitize

func (s Input) Sanitize() interface{}

Sanitize 自动判断类型并进行通用清理

func (Input) SanitizeString added in v0.8.0

func (s Input) SanitizeString(str string, args ...any) string

SanitizeString 清理字符串以防止 SQL 注入和 XSS 攻击

type SM4 added in v0.10.0

type SM4 struct {
	Text     string `json:"text" default:""`                // 待加密/解密的文本内容,实际加密或解密操作将基于该文本进行
	Key      string `json:"key" default:"jcbase.sm4_key__"` // 加密密钥,SM4算法要求密钥长度必须为16字节,用于加密和解密数据
	Iv       string `json:"iv" default:"jcbase.sm4_iv___"`  // 初始化向量(Initialization Vector),SM4算法要求IV长度必须为16字节,用于增强加密安全性
	Mode     string `json:"mode" default:"CBC"`             // 加密模式,可选值包括:CBC、GCM、CFB、OFB、CTR,指定加密操作使用的具体模式
	Encoding string `json:"encoding" default:"Std"`         // 输出/输入编码格式,可选值包括:Std(标准Base64)、Raw(无填充Base64)、RawURL(URL安全无填充Base64)、Hex(十六进制)
}

SM4 SM4加解密结构体 提供SM4对称加密算法的加解密功能

func (SM4) Decrypt added in v0.10.0

func (s SM4) Decrypt(plaintext *string) error

Decrypt 通用解密方法,根据Mode字段选择解密模式 参数:

  • plaintext: 解密后的明文输出指针

返回:

  • error: 解密失败时的错误信息

func (SM4) DecryptCBC added in v0.10.0

func (s SM4) DecryptCBC(plaintext *string) error

DecryptCBC 使用CBC模式解密数据 参数:

  • plaintext: 解密后的明文输出指针

返回:

  • error: 解密失败时的错误信息

func (SM4) DecryptGCM added in v0.10.0

func (s SM4) DecryptGCM(plaintext *string) error

DecryptGCM 使用GCM模式解密数据 参数:

  • plaintext: 解密后的明文输出指针

返回:

  • error: 解密失败时的错误信息

func (SM4) Encrypt added in v0.10.0

func (s SM4) Encrypt(cipherText *string) error

Encrypt 通用加密方法,根据Mode字段选择加密模式 参数:

  • cipherText: 加密后的密文输出指针

返回:

  • error: 加密失败时的错误信息

func (SM4) EncryptCBC added in v0.10.0

func (s SM4) EncryptCBC(cipherText *string) error

EncryptCBC 使用CBC模式加密数据 参数:

  • cipherText: 加密后的密文输出指针

返回:

  • error: 加密失败时的错误信息

func (SM4) EncryptGCM added in v0.10.0

func (s SM4) EncryptGCM(cipherText *string) error

EncryptGCM 使用GCM模式加密数据(推荐使用,提供认证加密) 参数:

  • cipherText: 加密后的密文输出指针

返回:

  • error: 加密失败时的错误信息

Jump to

Keyboard shortcuts

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