tydata-server/pkg/lzkit/crypto/generate.go
2025-01-10 00:09:25 +08:00

64 lines
1.4 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package crypto
import (
"crypto/rand"
"encoding/hex"
"io"
mathrand "math/rand"
"strconv"
"time"
)
// 生成AES-128密钥的函数符合市面规范
func GenerateSecretKey() (string, error) {
key := make([]byte, 16) // 16字节密钥
_, err := io.ReadFull(rand.Reader, key)
if err != nil {
return "", err
}
return hex.EncodeToString(key), nil
}
func GenerateSecretId() (string, error) {
// 创建一个字节数组,用于存储随机数据
bytes := make([]byte, 8) // 因为每个字节表示两个16进制字符
// 读取随机字节到数组中
_, err := rand.Read(bytes)
if err != nil {
return "", err
}
// 将字节数组转换为16进制字符串
return hex.EncodeToString(bytes), nil
}
// GenerateTransactionID 生成16位数的交易单号
func GenerateTransactionID() string {
length := 16
// 获取当前时间戳
timestamp := time.Now().UnixNano()
// 转换为字符串
timeStr := strconv.FormatInt(timestamp, 10)
// 生成随机数
mathrand.Seed(time.Now().UnixNano())
randomPart := strconv.Itoa(mathrand.Intn(1000000))
// 组合时间戳和随机数
combined := timeStr + randomPart
// 如果长度超出指定值,则截断;如果不够,则填充随机字符
if len(combined) >= length {
return combined[:length]
}
// 如果长度不够填充0
for len(combined) < length {
combined += strconv.Itoa(mathrand.Intn(10)) // 填充随机数
}
return combined
}