Documentation
¶
Overview ¶
* @Author: kamalyes 501893067@qq.com * @Date: 2024-10-23 17:37:08 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2024-10-23 17:58:07 * @FilePath: \go-toolbox\pkg\sign\aes.go * @Description: * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2024-11-10 21:51:58 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2024-11-11 00:55:15 * @FilePath: \go-toolbox\pkg\sign\base.go * @Description: * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2024-11-10 21:51:58 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2026-05-08 13:17:52 * @FilePath: \go-toolbox\pkg\sign\bcrypt.go * @Description: * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2024-11-10 21:51:58 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2026-05-29 13:15:55 * @FilePath: \go-toolbox\pkg\sign\decoder.go * @Description: * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2025-12-30 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-12-30 15:15:05 * @FilePath: \go-toolbox\pkg\sign\generator.go * @Description: 通用 HTTP 请求签名生成器 * * Copyright (c) 2025 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2025-06-05 13:35:59 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-06-05 17:22:17 * @FilePath: \go-toolbox\pkg\sign\message.go * @Description: * * Copyright (c) 2025 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2025-09-16 18:15:55 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-09-17 09:55:15 * @FilePath: \go-toolbox\pkg\sign\offset.go * @Description: * * Copyright (c) 2025 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2024-11-10 21:51:58 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2024-11-22 15:05:55 * @FilePath: \go-toolbox\pkg\sign\rsa.go * @Description: * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2026-03-28 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2026-03-28 00:00:00 * @FilePath: \go-toolbox\pkg\sign\totp.go * @Description: TOTP(基于时间的一次性密码)实现 * 基于RFC 6238算法,支持Google Authenticator等验证器应用 * 用于双因素认证(2FA)场景 * * Copyright (c) 2026 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2025-09-16 18:15:55 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-09-17 09:55:15 * @FilePath: \go-toolbox\pkg\sign\xor.go * @Description: * * Copyright (c) 2025 by kamalyes, All Rights Reserved.
Index ¶
- Constants
- Variables
- func AesDecrypt(cipherText string, key []byte) (string, error)
- func AesDecryptRaw(cipherBytes []byte, key []byte) (string, error)
- func AesDecryptWithIV(cipherText string, key, iv []byte) (string, error)
- func AesEncrypt(plainText string, key []byte) (string, error)
- func AesEncryptWithIV(plainText string, key, iv []byte) (string, error)
- func CompareHashAndPassword(hashed, data []byte) error
- func ComputeHashes(filePath string) (map[HashCryptoFunc]string, error)
- func ConsumeBackupCode(backupCodesJSON, code string) (bool, string)
- func DecryptOAEPWithPrivateKey(privateKey *rsa.PrivateKey, ciphertext []byte, hashFunc func() hash.Hash) ([]byte, error)
- func EncryptOAEPWithPublicKey(publicKey *rsa.PublicKey, plaintext []byte, hashFunc func() hash.Hash) ([]byte, error)
- func ExportRsaPrivateKeyToPEM(privateKey *rsa.PrivateKey) (string, error)
- func ExportRsaPublicKeyToPEM(publicKey *rsa.PublicKey) (string, error)
- func GenerateBackupCodes(count int) []string
- func GenerateByteKey(password string, length int) []byte
- func GenerateFromPassword(data []byte, cost ...int) ([]byte, error)
- func GenerateTOTPCode(secret string, config *TOTPConfig) (string, error)
- func GenerateTOTPSecret(secretLength int) string
- func GenerateTOTPURI(secret, account, issuer string, config *TOTPConfig) string
- func HmacSha256Base64(message string, secret string) string
- func HmacSha256Hex(message string, secret string) string
- func ParsePrivateKey(content []byte) (*rsa.PrivateKey, error)
- func ParsePublicKey(pemData []byte) (*rsa.PublicKey, error)
- func RSAPublicKeyToJWK(publicKey *rsa.PublicKey) (n, e string)
- func RegisterSigner(s Signer)
- func SHA256(text string) string
- func ValidateTOTPCode(secret, code string, config *TOTPConfig) bool
- type DecodeOption
- type Decoded
- type EncryptedDecoder
- type Generator
- type GeneratorConfig
- type GenericHMACSigner
- type HashCryptoFunc
- type Header
- type JSONSerializer
- type ProtonOffsetCipher
- type RsaCrypto
- type RsaKeyPair
- type RsaKeySize
- type Serializer
- type SignedMessage
- type Signer
- type SignerClient
- func (c *SignerClient[T]) Create(extraData T) (string, error)
- func (c *SignerClient[T]) Validate(signedStr string) (*SignedMessage[T], bool, error)
- func (c *SignerClient[T]) WithAlgorithm(alg HashCryptoFunc) (*SignerClient[T], error)
- func (c *SignerClient[T]) WithExpiration(duration time.Duration) *SignerClient[T]
- func (c *SignerClient[T]) WithIssuer(issuer string) *SignerClient[T]
- func (c *SignerClient[T]) WithSecretKey(key []byte) *SignerClient[T]
- func (c *SignerClient[T]) WithSerializer(s Serializer) *SignerClient[T]
- type TOTPBinding
- type TOTPBindingResult
- type TOTPConfig
- type XORCipher
Constants ¶
const ( PrivateKeyType = "PRIVATE KEY" // PKCS#8(推荐) RSAPrivateKeyType = "RSA PRIVATE KEY" // PKCS#1(兼容历史) PublicKeyType = "PUBLIC KEY" // PKIX(推荐) RSAPublicKeyType = "RSA PUBLIC KEY" // PKCS#1(兼容历史) )
PEM类型常量
Variables ¶
var ( ErrMissingAESKey = errors.New("aes key is required") ErrMissingCiphertext = errors.New("ciphertext is required") )
ErrMissingAESKey 缺少AES密钥
var ( ErrPrivateKey = errors.New("私钥文件错误") ErrPublicKey = errors.New("公钥解析错误") ErrEncryptFail = errors.New("加密失败") ErrDecryptFail = errors.New("解密失败") ErrPemBlockTypeFail = errors.New("PEM Block 类型不是 PUBLIC KEY 或 RSA PUBLIC KEY") ErrNotRsaPrivateKey = errors.New("不是RSA Private密钥") ErrNotRsaPublicKeyKey = errors.New("不是RSA Public密钥") ErrSaltEmpty = errors.New("盐值不能为空") // 新增盐值为空的错误 )
错误定义
var ErrUnsupportedAlgorithmHMAC = errors.New("不支持的 HMAC 算法")
ErrUnsupportedAlgorithmHMAC 表示不支持的 HMAC 算法错误
var SupportHMACCryptoFunc = map[HashCryptoFunc]func() hash.Hash{ AlgorithmMD5: md5.New, AlgorithmSHA1: sha1.New, AlgorithmSHA224: sha256.New224, AlgorithmSHA256: sha256.New, AlgorithmSHA384: sha512.New384, AlgorithmSHA512: sha512.New, }
SupportHMACCryptoFunc 支持的 HMAC 哈希算法映射,key 是算法名称,value 是哈希函数构造器
Functions ¶
func AesDecryptRaw ¶
AesDecryptRaw 解密函数(直接接收原始字节,不经过 base64 解码) 适用于上层已通过 JSON/protojson 对 bytes 字段做 base64 解码的场景(如 grpc-gateway 的 body 绑定) cipherBytes 格式:iv(16字节) + aes-cbc-pkcs7-ciphertext
func AesDecryptWithIV ¶
AesDecryptWithIV 使用自定义 IV 的 AES-CBC-PKCS7 解密 [EN] AES-CBC-PKCS7 decryption with custom IV
func AesEncryptWithIV ¶
AesEncryptWithIV 使用自定义 IV 的 AES-CBC-PKCS7 加密 [EN] AES-CBC-PKCS7 encryption with custom IV
func CompareHashAndPassword ¶
CompareHashAndPassword 校验数据与 bcrypt 哈希是否匹配 匹配返回 nil,不匹配返回 bcrypt.ErrMismatchedHashAndPassword
func ComputeHashes ¶
func ComputeHashes(filePath string) (map[HashCryptoFunc]string, error)
ComputeHashes 计算文件的多种哈希值,优化为只读一次文件
func ConsumeBackupCode ¶
ConsumeBackupCode 从 JSON 格式的备份码数组中消耗一个码 backupCodesJSON: JSON数组字符串,如 ["ABCD1234","EFGH5678"] code: 要消耗的备份码 返回:是否消耗成功,剩余备份码的JSON字符串
func DecryptOAEPWithPrivateKey ¶
func DecryptOAEPWithPrivateKey(privateKey *rsa.PrivateKey, ciphertext []byte, hashFunc func() hash.Hash) ([]byte, error)
DecryptOAEPWithPrivateKey 使用 RSA 私钥进行 OAEP 解密(简易版本,无需创建 RsaCrypto 实例)
func EncryptOAEPWithPublicKey ¶
func EncryptOAEPWithPublicKey(publicKey *rsa.PublicKey, plaintext []byte, hashFunc func() hash.Hash) ([]byte, error)
EncryptOAEPWithPublicKey 使用 RSA 公钥进行 OAEP 加密(简易版本,无需创建 RsaCrypto 实例)
func ExportRsaPrivateKeyToPEM ¶
func ExportRsaPrivateKeyToPEM(privateKey *rsa.PrivateKey) (string, error)
ExportRsaPrivateKeyToPEM 将 RSA 私钥导出为 PEM 格式
func ExportRsaPublicKeyToPEM ¶
ExportRsaPublicKeyToPEM 将 RSA 公钥导出为 PEM 格式
func GenerateBackupCodes ¶
GenerateBackupCodes 生成指定数量的恢复码 每个恢复码为8位随机十六进制字符串
func GenerateByteKey ¶
GenerateByteKey 生成一个指定字节的密钥
func GenerateFromPassword ¶
GenerateFromPassword 使用 bcrypt 对数据进行哈希 cost: 可选的哈希成本因子,不传则使用默认值 bcrypt.DefaultCost(10)
func GenerateTOTPCode ¶
func GenerateTOTPCode(secret string, config *TOTPConfig) (string, error)
GenerateTOTPCode 根据密钥和当前时间生成TOTP验证码
func GenerateTOTPSecret ¶
GenerateTOTPSecret 生成TOTP密钥(Base32编码的随机字节) secretLength: 密钥字节长度,推荐20
func GenerateTOTPURI ¶
func GenerateTOTPURI(secret, account, issuer string, config *TOTPConfig) string
GenerateTOTPURI 构建TOTP URI(otpauth://totp/...) 供Google Authenticator等验证器应用扫描
func HmacSha256Base64 ¶
HmacSha256Base64 计算hmac
func HmacSha256Hex ¶
HmacSha256Hex 字符串计算sha256之后转hex
func ParsePrivateKey ¶
func ParsePrivateKey(content []byte) (*rsa.PrivateKey, error)
ParsePrivateKey 解析PEM格式的私钥
func ParsePublicKey ¶
ParsePublicKey 解析 PEM 格式的公钥
func RSAPublicKeyToJWK ¶
RSAPublicKeyToJWK 将 RSA 公钥转换为 JWK 格式的模数(n)和指数(e)
func RegisterSigner ¶
func RegisterSigner(s Signer)
RegisterSigner 注册一个签名器,将其算法名称作为键,签名器实例作为值 方便后续通过算法名称获取对应的签名器
func ValidateTOTPCode ¶
func ValidateTOTPCode(secret, code string, config *TOTPConfig) bool
ValidateTOTPCode 验证TOTP验证码 基于RFC 6238算法,允许前后Skew个时间窗口
Types ¶
type DecodeOption ¶
type DecodeOption func(*EncryptedDecoder)
DecodeOption 解密器选项
func WithRawCiphertext ¶
func WithRawCiphertext() DecodeOption
WithRawCiphertext 设置密文为原始字节模式 启用后 Decrypt 直接接收 iv+ciphertext 原始字节,不再做 base64 解码 适用于 grpc-gateway 等 JSON marshaler 已对 bytes 字段做 base64 解码的场景
type Decoded ¶
func DecodeJSON ¶
func DecodeJSON[T any](d *EncryptedDecoder, ciphertext []byte) (*Decoded[T], error)
DecodeJSON 解密JSON
func DecodeProtoJSON ¶
func DecodeProtoJSON[T proto.Message](d *EncryptedDecoder, ciphertext []byte, newPayload func() T) (*Decoded[T], error)
DecodeProtoJSON 解密Proto JSON
type EncryptedDecoder ¶
type EncryptedDecoder struct {
// contains filtered or unexported fields
}
EncryptedDecoder 解密器
func NewEncryptedDecoder ¶
func NewEncryptedDecoder(opts ...DecodeOption) *EncryptedDecoder
NewEncryptedDecoder 创建解密器
func (*EncryptedDecoder) DecodeJSONTo ¶
func (d *EncryptedDecoder) DecodeJSONTo(ciphertext []byte, target any) ([]byte, error)
DecodeJSONTo 解密JSON到目标
func (*EncryptedDecoder) DecodeProtoJSONTo ¶
func (d *EncryptedDecoder) DecodeProtoJSONTo(ciphertext []byte, target proto.Message) ([]byte, error)
DecodeProtoJSONTo 解密Proto JSON到目标
type Generator ¶
type Generator struct {
// contains filtered or unexported fields
}
Generator 签名生成器
func (*Generator) GenerateHeaders ¶
func (g *Generator) GenerateHeaders(method, path, body string, headers map[string]string, queryParams url.Values) map[string]string
GenerateHeaders 生成签名相关的 headers method: HTTP 方法(GET, POST 等) path: 请求路径 body: 请求体 headers: 原始 headers queryParams: 查询参数 返回:包含签名的完整 headers
type GeneratorConfig ¶
type GeneratorConfig struct {
Enabled bool // 是否启用签名
HeaderName string // 签名 header 名称,默认 "X-Sign"
TimestampHeader string // 时间戳 header 名称,默认 "X-Timestamp"
NonceHeader string // 随机数 header 名称,默认 "X-Nonce"
SecretKey string // 签名密钥
Algorithm HashCryptoFunc // 签名算法,默认 SHA256
IncludeBody bool // 是否包含请求体
IncludeQuery bool // 是否包含查询参数
IncludeHeaders []string // 需要包含在签名中的 header 列表
Format string // 自定义签名格式模板
Extra map[string]string // 额外的 header 参数
}
GeneratorConfig 签名生成器配置
type GenericHMACSigner ¶
type GenericHMACSigner struct {
// contains filtered or unexported fields
}
GenericHMACSigner 是一个基于 HMAC 的通用签名器
func NewGenericHMACSigner ¶
func NewGenericHMACSigner(algorithm HashCryptoFunc, hashFunc func() hash.Hash) *GenericHMACSigner
NewGenericHMACSigner 创建一个新的 GenericHMACSigner 实例 algorithm 参数是算法名称,hashFunc 是对应的哈希函数构造器
func (*GenericHMACSigner) Algorithm ¶
func (s *GenericHMACSigner) Algorithm() HashCryptoFunc
Algorithm 返回签名算法名称
type HashCryptoFunc ¶
type HashCryptoFunc string
定义算法名称常量
const ( AlgorithmMD5 HashCryptoFunc = "MD5" AlgorithmSHA1 HashCryptoFunc = "SHA1" AlgorithmSHA224 HashCryptoFunc = "SHA224" AlgorithmSHA256 HashCryptoFunc = "SHA256" AlgorithmSHA384 HashCryptoFunc = "SHA384" AlgorithmSHA512 HashCryptoFunc = "SHA512" )
type Header ¶
type Header struct {
Alg HashCryptoFunc // 签名算法名称(如 "HMAC-SHA256")
Send string // 随机字符串,用于防重放
Issuer string // 签发人
IssuedAt int64 // 签发时间,微秒级
Expiration int64 // 过期时间,单位为微秒
}
Header 是 JWT 的头部结构体
type JSONSerializer ¶
type JSONSerializer struct{}
JSONSerializer 是 Serializer 接口的 JSON 实现,使用标准库 encoding/json
type ProtonOffsetCipher ¶
type ProtonOffsetCipher struct {
P int // 质数
C int // 偏移量
M int // 模数
// contains filtered or unexported fields
}
ProtonOffsetCipher 结构体定义
func NewProtonOffsetCipher ¶
func NewProtonOffsetCipher() *ProtonOffsetCipher
NewProtonOffsetCipher 创建一个新的 ProtonOffsetCipher 实例,使用默认偏移量
func NewProtonOffsetCipherWithPCM ¶
func NewProtonOffsetCipherWithPCM(p, c, m int) *ProtonOffsetCipher
NewProtonOffsetCipherWithPCM 创建一个新的 ProtonOffsetCipher 实例,使用指定的偏移量
type RsaCrypto ¶
type RsaCrypto interface {
EncryptSalt(input []byte, salt []byte) ([]byte, error)
EncryptRandSalt(input []byte, saltLength ...int) ([]byte, []byte, error)
Decrypt(input []byte) ([]byte, error)
DecryptBase64(input string) ([]byte, error)
GetPrivateKey() *rsa.PrivateKey
GetPublicKey() *rsa.PublicKey
}
RsaCrypto 定义了RSA加解密器的接口
func NewRsaCryptoFromKeys ¶
func NewRsaCryptoFromKeys(privateKey *rsa.PrivateKey, publicKey *rsa.PublicKey, hashFunc func() hash.Hash) RsaCrypto
NewRsaCryptoFromKeys 根据公钥和私钥创建RSA加解密器
func NewRsaCryptoFromPrivateFile ¶
NewRsaCryptoFromPrivateFile 根据私钥文件创建RSA加解密器
type RsaKeyPair ¶
type RsaKeyPair struct {
PrivateKey *rsa.PrivateKey
PublicKey *rsa.PublicKey
}
RsaKeyPair 包含RSA密钥对
func GenerateRsaKeyPair ¶
func GenerateRsaKeyPair(keySize RsaKeySize) (*RsaKeyPair, error)
GenerateRsaKeyPair 生成指定大小的 RSA 密钥对
type RsaKeySize ¶
type RsaKeySize int
RsaKeySize 定义了支持的RSA密钥大小
const ( RsaKeySize512 RsaKeySize = 512 RsaKeySize1024 RsaKeySize = 1024 RsaKeySize2048 RsaKeySize = 2048 RsaKeySize4096 RsaKeySize = 4096 )
type Serializer ¶
Serializer 定义了序列化和反序列化的接口,方便支持多种数据格式 Marshal 将对象序列化为字节切片 Unmarshal 将字节切片反序列化为对象
type SignedMessage ¶
SignedMessage 是泛型结构,包含签名算法名称、随机字符串、时间戳和额外数据 其中: - Alg 字段表示本消息使用的签名算法名称,便于验证时动态选择签名器 - Send 是随机字符串,用于防止重放攻击,保证每条消息唯一 - GenUnixMicro 是消息生成时的时间戳,单位为微秒,方便做时效校验 - ExtraData 是用户自定义的泛型数据,支持任意结构
type Signer ¶
type Signer interface {
// Algorithm 返回签名算法名称
Algorithm() HashCryptoFunc
// Sign 计算 data 的签名,使用给定的 key,返回签名字节切片或错误
Sign(data, key []byte) ([]byte, error)
// Verify 验证 data 的签名是否正确,使用给定的 key 和签名 signature,返回验证结果和错误
Verify(data, key, signature []byte) (bool, error)
}
Signer 接口定义了签名和验证方法
func GetSigner ¶
func GetSigner(alg HashCryptoFunc) (Signer, error)
GetSigner 根据算法名称获取对应的签名器实例,如果不存在则返回错误
func NewHMACSigner ¶
func NewHMACSigner(algorithm HashCryptoFunc) (Signer, error)
NewHMACSigner 根据算法名称创建对应的通用 HMAC 签名器
type SignerClient ¶
type SignerClient[T any] struct { // contains filtered or unexported fields }
SignerClient 是带状态的签名客户端,支持复用 secretKey、算法和签名器,且并发安全。
func (*SignerClient[T]) Create ¶
func (c *SignerClient[T]) Create(extraData T) (string, error)
Create 创建签名消息字符串,内部使用客户端状态
func (*SignerClient[T]) Validate ¶
func (c *SignerClient[T]) Validate(signedStr string) (*SignedMessage[T], bool, error)
Validate 验证签名消息字符串,返回负载、是否有效和错误
func (*SignerClient[T]) WithAlgorithm ¶
func (c *SignerClient[T]) WithAlgorithm(alg HashCryptoFunc) (*SignerClient[T], error)
WithAlgorithm 设置算法及对应签名器
func (*SignerClient[T]) WithExpiration ¶
func (c *SignerClient[T]) WithExpiration(duration time.Duration) *SignerClient[T]
WithExpiration 设置过期时间
func (*SignerClient[T]) WithIssuer ¶
func (c *SignerClient[T]) WithIssuer(issuer string) *SignerClient[T]
WithIssuer 设置签发人
func (*SignerClient[T]) WithSecretKey ¶
func (c *SignerClient[T]) WithSecretKey(key []byte) *SignerClient[T]
WithSecretKey 设置密钥
func (*SignerClient[T]) WithSerializer ¶
func (c *SignerClient[T]) WithSerializer(s Serializer) *SignerClient[T]
WithSerializer 设置序列化器
type TOTPBinding ¶
type TOTPBinding struct {
DeviceID string `json:"device_id"`
Secret string `json:"secret"`
QRCodeURI string `json:"qr_code_uri"`
BackupCodes []string `json:"backup_codes"`
TOTPConfig TOTPConfig `json:"totp_config"`
}
TOTPBinding 包含待绑定的TOTP设备信息
func GenerateTOTPBinding ¶
func GenerateTOTPBinding(deviceID, account, issuer string, secretLength, backupCodeCount int, config *TOTPConfig) *TOTPBinding
ValidateTOTPCode 验证TOTP验证码 基于RFC 6238算法,允许前后Skew个时间窗口 GenerateTOTPBinding generates a TOTP secret, backup codes, and QR URI for a device.
type TOTPBindingResult ¶
type TOTPBindingResult struct {
DeviceID string
Secret string
QRCodeURI string
BackupCodes []string
}
TOTPBindingResult 包含TOTP绑定结果信息
type TOTPConfig ¶
type TOTPConfig struct {
Digits int // 验证码位数,默认6
Period int // 时间步长(秒),默认30
Skew int // 允许的时间窗口偏移量,默认1(前后各1个窗口)
Algorithm string // 哈希算法,默认SHA1
}
TOTPConfig TOTP配置参数