service.xpcool.com/common/tools/cryptox/cryptox.go
夏犀麟 8d5f2c65ae feat(common): 新增公共模块 common/tools 及项目上下文记忆体系
- common/tools 工具模块,10 个子功能:md5/cryptox/uuid/random/timex/convertx/strx/slicex/ip/filex(薄封装 GoFrame 内置组件)
- AGENTS.md 项目智能体说明书(架构、规范、命令、记忆体系索引)
- docs/change-log/2026-08-24.md 本次请求与变更记录
- .gitignore 排除 .workbuddy/;PROJECT_STRUCTURE.md 补充目录树
2026-08-24 17:18:10 +08:00

81 lines
2.5 KiB
Go

// Package cryptox provides AES/DES encryption helpers with base64 output,
// built on top of gaes and gdes.
//
// Keys: any-length secrets are accepted — they are normalized to the exact
// key size internally, so callers do not need to manage key lengths.
package cryptox
import (
"crypto/md5"
"encoding/base64"
"github.com/gogf/gf/v2/crypto/gaes"
"github.com/gogf/gf/v2/crypto/gdes"
"github.com/gogf/gf/v2/errors/gerror"
)
const (
aesKeySize = 16 // AES-128 key size in bytes
desKeySize = 8 // DES key size in bytes
)
// normalizeKey derives a fixed-size key from an arbitrary-length secret.
func normalizeKey(secret string, size int) []byte {
key := []byte(secret)
if len(key) == size {
return key
}
sum := md5.Sum([]byte(secret))
out := make([]byte, size)
for i := 0; i < size; i++ {
out[i] = sum[i%len(sum)]
}
return out
}
// AesEncrypt encrypts plainText with AES-128-CBC using a key derived from
// secret, and returns the ciphertext encoded in base64.
func AesEncrypt(plainText, secret string) (string, error) {
out, err := gaes.Encrypt([]byte(plainText), normalizeKey(secret, aesKeySize))
if err != nil {
return "", gerror.Wrap(err, `AesEncrypt failed`)
}
return base64.StdEncoding.EncodeToString(out), nil
}
// AesDecrypt decrypts the base64-encoded cipherText produced by AesEncrypt.
func AesDecrypt(cipherText, secret string) (string, error) {
data, err := base64.StdEncoding.DecodeString(cipherText)
if err != nil {
return "", gerror.Wrap(err, `base64 decode failed`)
}
out, err := gaes.Decrypt(data, normalizeKey(secret, aesKeySize))
if err != nil {
return "", gerror.Wrap(err, `AesDecrypt failed`)
}
return string(out), nil
}
// DesEncrypt encrypts plainText with DES-ECB (PKCS5 padding) using a key
// derived from secret, and returns the ciphertext encoded in base64.
func DesEncrypt(plainText, secret string) (string, error) {
out, err := gdes.EncryptECB([]byte(plainText), normalizeKey(secret, desKeySize), gdes.PKCS5PADDING)
if err != nil {
return "", gerror.Wrap(err, `DesEncrypt failed`)
}
return base64.StdEncoding.EncodeToString(out), nil
}
// DesDecrypt decrypts the base64-encoded cipherText produced by DesEncrypt.
func DesDecrypt(cipherText, secret string) (string, error) {
data, err := base64.StdEncoding.DecodeString(cipherText)
if err != nil {
return "", gerror.Wrap(err, `base64 decode failed`)
}
out, err := gdes.DecryptECB(data, normalizeKey(secret, desKeySize), gdes.PKCS5PADDING)
if err != nil {
return "", gerror.Wrap(err, `DesDecrypt failed`)
}
return string(out), nil
}