Documentation
¶
Overview ¶
Example (TaskConfiguration) ¶
Example: Real-world usage with task configuration
package main
import (
"fmt"
"log"
"github.com/tx7do/go-utils/crypto"
)
func main() {
// Initialize encryption (typically done at app startup)
crypto.InitGlobalEncryptor("production-secret-key-min-32-chars", true)
// Simulate task configuration with sensitive data
taskConfig := `{
"host": "imap.gmail.com",
"port": 993,
"username": "user@example.com",
"password": "super-secret-password",
"tls": true
}`
// Before saving to database, encrypt the configuration
encryptedConfig, err := crypto.EncryptIfNeeded(taskConfig)
if err != nil {
log.Fatal(err)
}
// Store in database (simulated)
fmt.Println("Stored in DB:", crypto.IsEncrypted(encryptedConfig))
// When reading from database, decrypt the configuration
decryptedConfig, err := crypto.DecryptIfNeeded(encryptedConfig)
if err != nil {
log.Fatal(err)
}
// Use the decrypted configuration
fmt.Println("Can use config:", decryptedConfig == taskConfig)
}
Output: Stored in DB: true Can use config: true
Index ¶
- Constants
- Variables
- func AesDecrypt(cryptedText, key, iv []byte) ([]byte, error)
- func AesEncrypt(plainText, key, iv []byte) ([]byte, error)
- func DecryptIfNeeded(ciphertext string) (string, error)
- func DecryptPayload(payload map[string]interface{}) (map[string]interface{}, error)
- func EncryptIfNeeded(plaintext string) (string, error)
- func EncryptPayload(payload map[string]interface{}, reservedKeys ...string) (map[string]interface{}, error)
- func GenerateAESKey(length int) ([]byte, error)
- func GenerateSM4Key() ([]byte, error)
- func HasEncryptedPayload(payload map[string]interface{}) bool
- func InitGlobalEncryptor(key string, enabled bool) error
- func IsEncrypted(data string) bool
- func MustDecryptPayload(payload map[string]interface{}) map[string]interface{}
- func MustEncryptPayload(payload map[string]interface{}, reservedKeys ...string) map[string]interface{}
- func PKCS5Padding(plaintext []byte, blockSize int) []byte
- func PKCS5UnPadding(origData []byte) []byte
- func ParseECDSAPublicKey(data []byte) (*ecdsa.PublicKey, error)
- func SHA256Sum(data []byte) []byte
- func SHA512Sum(data []byte) []byte
- func SignData(data string) (string, error)
- func VerifyData(data, signature string) bool
- type AESCipher
- type AESGCMCipher
- type Cipher
- type ECDHCipher
- type ECDSACipher
- type Encryptor
- type HMAC
- type Hasher
- type KeyExchanger
- type RSACipher
- func (r *RSACipher) Decrypt(ciphertext []byte) ([]byte, error)
- func (r *RSACipher) Encrypt(plain []byte) ([]byte, error)
- func (r *RSACipher) ExportPrivateKey() (string, error)
- func (r *RSACipher) ExportPublicKey() (string, error)
- func (r *RSACipher) Name() string
- func (r *RSACipher) PrivateKey() *rsa.PrivateKey
- func (r *RSACipher) PublicKey() *rsa.PublicKey
- type SHA256Hasher
- type SHA512Hasher
- type SM2Cipher
- func (s *SM2Cipher) Decrypt(ciphertext []byte) ([]byte, error)
- func (s *SM2Cipher) DecryptAsn1(ciphertext []byte) ([]byte, error)
- func (s *SM2Cipher) Encrypt(plain []byte) ([]byte, error)
- func (s *SM2Cipher) EncryptAsn1(plain []byte) ([]byte, error)
- func (s *SM2Cipher) Name() string
- func (s *SM2Cipher) PrivateKey() *sm2.PrivateKey
- func (s *SM2Cipher) PublicKey() *sm2.PublicKey
- func (s *SM2Cipher) Sign(digest []byte) (string, error)
- func (s *SM2Cipher) Verify(data []byte, signature string) (bool, error)
- type SM3Hasher
- type SM4Cipher
- type Signer
- type Verifier
Examples ¶
Constants ¶
const ( // EncryptedConfigKey is the key used to store encrypted configuration in task payload EncryptedConfigKey = "_encrypted_config" // IsEncryptedKey indicates if the payload contains encrypted data IsEncryptedKey = "_is_encrypted" )
const (
// EncryptedPrefix is added to encrypted data to distinguish from plaintext
EncryptedPrefix = "enc:"
)
Variables ¶
var ( ErrInvalidKey = errors.New("encryption key must be at least 32 bytes") ErrInvalidCiphertext = errors.New("invalid ciphertext") ErrDecryptionFailed = errors.New("decryption failed") )
var DefaultAESKey = []byte("f51d66a73d8a0927")
DefaultAESKey 默认AES密钥(16字节)
Functions ¶
func DecryptIfNeeded ¶ added in v0.0.4
DecryptIfNeeded decrypts data if it's encrypted
Example ¶
package main
import (
"fmt"
"log"
"github.com/tx7do/go-utils/crypto"
)
func main() {
// Initialize global encryptor
crypto.InitGlobalEncryptor("global-secret-key", true)
// Encrypt some data
encrypted, _ := crypto.EncryptIfNeeded("sensitive data")
// Decrypt using global encryptor
decrypted, err := crypto.DecryptIfNeeded(encrypted)
if err != nil {
log.Fatal(err)
}
fmt.Println("Decrypted:", decrypted == "sensitive data")
}
Output: Decrypted: true
func DecryptPayload ¶ added in v0.0.4
DecryptPayload decrypts the payload if it contains encrypted configuration Returns the decrypted payload map
func EncryptIfNeeded ¶ added in v0.0.4
EncryptIfNeeded encrypts data if the global encryptor is initialized
Example ¶
package main
import (
"fmt"
"log"
"github.com/tx7do/go-utils/crypto"
)
func main() {
// Initialize global encryptor
crypto.InitGlobalEncryptor("global-secret-key", true)
// Use global encryptor for convenience
encrypted, err := crypto.EncryptIfNeeded("sensitive data")
if err != nil {
log.Fatal(err)
}
fmt.Println("Encrypted:", crypto.IsEncrypted(encrypted))
}
Output: Encrypted: true
func EncryptPayload ¶ added in v0.0.4
func EncryptPayload(payload map[string]interface{}, reservedKeys ...string) (map[string]interface{}, error)
EncryptPayload encrypts the entire payload and returns a map with encrypted data This is used to store encrypted configuration in Redis/Asynq. reservedKeys 列出的键以明文保留在外层,供无需解密的路由/调度层读取 (如任务系统的 "task_id"/"task_type")。
安全契约:仅当真正完成加密时才置 IsEncryptedKey=true。若全局加密器未配置 (EncryptIfNeeded 返回明文原值),则不标记为已加密,避免调用方误判明文为密文 而在解密侧产生"解密失败"或静默数据错乱。
func HasEncryptedPayload ¶ added in v0.0.4
HasEncryptedPayload checks if the payload contains encrypted configuration
func InitGlobalEncryptor ¶ added in v0.0.4
InitGlobalEncryptor initializes the global encryptor instance
func IsEncrypted ¶ added in v0.0.4
IsEncrypted checks if the given string is encrypted (has the prefix)
Example ¶
package main
import (
"fmt"
"github.com/tx7do/go-utils/crypto"
)
func main() {
encryptedData := "enc:SGVsbG8gV29ybGQh"
plaintextData := "Hello, World!"
fmt.Println("Encrypted:", crypto.IsEncrypted(encryptedData))
fmt.Println("Plaintext:", crypto.IsEncrypted(plaintextData))
}
Output: Encrypted: true Plaintext: false
func MustDecryptPayload ¶ added in v0.0.4
MustDecryptPayload decrypts payload and panics on error (useful for testing)
func MustEncryptPayload ¶ added in v0.0.4
func MustEncryptPayload(payload map[string]interface{}, reservedKeys ...string) map[string]interface{}
MustEncryptPayload encrypts payload and panics on error (useful for testing)
func ParseECDSAPublicKey ¶ added in v0.0.3
ParseECDSAPublicKey 从 X.509 PKIX/DER 编码字节解析ECDSA公钥 是 ECDSACipher.PublicKeyBytes 的逆操作
func SignData ¶ added in v0.0.4
SignData 用全局加密器密钥对 data 计算 HMAC-SHA256 签名(hex 编码)。 用于签名 URL 场景(签名即凭证,需配合有效期由调用方自行拼接校验)。 全局加密器未初始化时返回错误——此时签名能力不可用,调用方应拒绝 生成签名 URL 而非降级为无签名。
func VerifyData ¶ added in v0.0.4
VerifyData 校验 SignData 生成的签名(恒定时间比较)。
Types ¶
type AESCipher ¶
type AESCipher struct {
// contains filtered or unexported fields
}
func NewAESCipher ¶
type AESGCMCipher ¶ added in v0.0.2
type AESGCMCipher struct {
// contains filtered or unexported fields
}
func NewAESGCMCipher ¶ added in v0.0.2
func NewAESGCMCipher(key []byte) (*AESGCMCipher, error)
NewAESGCMCipher 创建AES-GCM模式的Cipher
func (*AESGCMCipher) Decrypt ¶ added in v0.0.2
func (a *AESGCMCipher) Decrypt(ciphertext []byte) ([]byte, error)
Decrypt 使用AES-GCM解密
func (*AESGCMCipher) Encrypt ¶ added in v0.0.2
func (a *AESGCMCipher) Encrypt(plain []byte) ([]byte, error)
Encrypt 使用AES-GCM加密
func (*AESGCMCipher) Name ¶ added in v0.0.2
func (a *AESGCMCipher) Name() string
type Cipher ¶
type Cipher interface {
// Encrypt 使用指定的密钥和初始化向量(IV)加密明文数据,返回加密后的数据
Encrypt(plain []byte) ([]byte, error)
// Decrypt 使用指定的密钥和初始化向量(IV)解密密文数据,返回解密后的数据
Decrypt(cipher []byte) ([]byte, error)
// Name 返回算法名称
Name() string
}
Cipher 定义了加密算法的接口,支持加密和解密操作
type ECDHCipher ¶
type ECDHCipher struct {
// contains filtered or unexported fields
}
func (*ECDHCipher) DeriveSharedSecret ¶
func (e *ECDHCipher) DeriveSharedSecret(peerPubBytes []byte) ([]byte, error)
DeriveSharedSecret 计算共享密钥
func (*ECDHCipher) PrivateKey ¶
func (e *ECDHCipher) PrivateKey() *ecdh.PrivateKey
PrivateKey 获取私钥(仅用于安全存储,禁止对外泄露)
func (*ECDHCipher) PublicKey ¶
func (e *ECDHCipher) PublicKey() *ecdh.PublicKey
PublicKey 获取公钥(用于导出、传输给对方)
func (*ECDHCipher) PublicKeyBytes ¶
func (e *ECDHCipher) PublicKeyBytes() []byte
PublicKeyBytes 获取公钥字节
type ECDSACipher ¶
type ECDSACipher struct {
// contains filtered or unexported fields
}
func NewECDSACipherFromKey ¶ added in v0.0.3
func NewECDSACipherFromKey(priv *ecdsa.PrivateKey, pub *ecdsa.PublicKey) *ECDSACipher
NewECDSACipherFromKey 用已有密钥初始化
func (*ECDSACipher) PrivateKey ¶
func (e *ECDSACipher) PrivateKey() *ecdsa.PrivateKey
func (*ECDSACipher) PublicKeyBytes ¶
func (e *ECDSACipher) PublicKeyBytes() []byte
PublicKeyBytes 导出公钥字节(X.509 PKIX/DER编码) 可用 ParseECDSAPublicKey 或 x509.ParsePKIXPublicKey 解析
type Encryptor ¶ added in v0.0.4
type Encryptor struct {
// contains filtered or unexported fields
}
Encryptor provides AES-256-GCM encryption/decryption functionality
func GetGlobalEncryptor ¶ added in v0.0.4
func GetGlobalEncryptor() *Encryptor
GetGlobalEncryptor returns the global encryptor instance
func NewEncryptor ¶ added in v0.0.4
NewEncryptor creates a new encryptor with the given key The key will be hashed to ensure it's exactly 32 bytes for AES-256
func (*Encryptor) Decrypt ¶ added in v0.0.4
Decrypt decrypts the ciphertext using AES-256-GCM Expects base64-encoded ciphertext with "enc:" prefix
Example ¶
package main
import (
"fmt"
"log"
"github.com/tx7do/go-utils/crypto"
)
func main() {
// Create an encryptor with a secret key
encryptor, err := crypto.NewEncryptor("my-secret-key")
if err != nil {
log.Fatal(err)
}
// Encrypt some data
plaintext := `{"username":"admin","password":"secret123"}`
encrypted, _ := encryptor.Encrypt(plaintext)
// Decrypt it back
decrypted, err := encryptor.Decrypt(encrypted)
if err != nil {
log.Fatal(err)
}
fmt.Println("Decryption successful:", decrypted == plaintext)
}
Output: Decryption successful: true
Example (BackwardCompatibility) ¶
package main
import (
"fmt"
"log"
"github.com/tx7do/go-utils/crypto"
)
func main() {
// Create an encryptor
encryptor, err := crypto.NewEncryptor("my-secret-key")
if err != nil {
log.Fatal(err)
}
// Legacy unencrypted data (no "enc:" prefix)
legacyData := `{"username":"admin","password":"old-data"}`
// Decrypt handles unencrypted data gracefully
decrypted, err := encryptor.Decrypt(legacyData)
if err != nil {
log.Fatal(err)
}
// Returns the data as-is for backward compatibility
fmt.Println("Legacy data handled:", decrypted == legacyData)
}
Output: Legacy data handled: true
func (*Encryptor) Encrypt ¶ added in v0.0.4
Encrypt encrypts the plaintext using AES-256-GCM Returns base64-encoded ciphertext with "enc:" prefix
Example ¶
package main
import (
"fmt"
"log"
"github.com/tx7do/go-utils/crypto"
)
func main() {
// Create an encryptor with a secret key
encryptor, err := crypto.NewEncryptor("my-secret-key")
if err != nil {
log.Fatal(err)
}
// Encrypt sensitive data
plaintext := `{"username":"admin","password":"secret123"}`
encrypted, err := encryptor.Encrypt(plaintext)
if err != nil {
log.Fatal(err)
}
// Encrypted data has the "enc:" prefix
fmt.Println("Data encrypted:", crypto.IsEncrypted(encrypted))
}
Output: Data encrypted: true
func (*Encryptor) MustDecrypt ¶ added in v0.0.4
MustDecrypt decrypts data and panics on error (useful for testing)
func (*Encryptor) MustEncrypt ¶ added in v0.0.4
MustEncrypt encrypts data and panics on error (useful for testing)
type Hasher ¶
type Hasher interface {
// Sum 计算输入数据的哈希值,返回哈希结果
Sum(data []byte) ([]byte, error)
// Name 返回哈希算法名称
Name() string
}
Hasher 定义了哈希算法的接口,支持计算数据的哈希值
type KeyExchanger ¶
type KeyExchanger interface {
DeriveSharedSecret(peerPubBytes []byte) ([]byte, error)
// PublicKeyBytes 获取本地公钥字节
PublicKeyBytes() []byte
}
KeyExchanger 定义了密钥协商算法的接口 适用于ECDH、SM2密钥交换等场景
type RSACipher ¶
type RSACipher struct {
// contains filtered or unexported fields
}
func NewRSACipherFromKey ¶
func NewRSACipherFromKey(priv *rsa.PrivateKey, pub *rsa.PublicKey) *RSACipher
NewRSACipherFromKey 用已有密钥初始化
func (*RSACipher) ExportPrivateKey ¶
ExportPrivateKey 导出私钥PEM
func (*RSACipher) ExportPublicKey ¶
ExportPublicKey 导出公钥PEM
type SHA256Hasher ¶
type SHA256Hasher struct{}
func (*SHA256Hasher) Name ¶
func (h *SHA256Hasher) Name() string
type SHA512Hasher ¶
type SHA512Hasher struct{}
func (*SHA512Hasher) Name ¶
func (h *SHA512Hasher) Name() string
type SM2Cipher ¶
type SM2Cipher struct {
// contains filtered or unexported fields
}
SM2Cipher 实现 Cipher 接口,支持国密SM2加解密 仅适用于小数据块加密(如密钥交换),不适合大数据流 生产环境请妥善管理私钥
func NewSM2CipherFromKey ¶
func NewSM2CipherFromKey(priv *sm2.PrivateKey, pub *sm2.PublicKey) *SM2Cipher
NewSM2CipherFromKey 用已有密钥初始化
func (*SM2Cipher) DecryptAsn1 ¶
DecryptAsn1 解密ASN.1格式密文
func (*SM2Cipher) EncryptAsn1 ¶
EncryptAsn1 加密并输出ASN.1格式(更通用,兼容多数平台)
func (*SM2Cipher) PrivateKey ¶
func (s *SM2Cipher) PrivateKey() *sm2.PrivateKey
PrivateKey 获取私钥(仅用于安全存储,禁止对外泄露)
type SM4Cipher ¶
type SM4Cipher struct {
// contains filtered or unexported fields
}
SM4Cipher 实现国密SM4对称加密算法(ECB模式,适合小数据块)