24 Commits

Author SHA1 Message Date
徐涛
30ddec3409 feat(hash): 添加 BLAKE3 校验和算法支持
- 在 `README.md` 中将 BLAKE3 校验和算法标记为已完成
- 引入 `lukechampine.com/blake3` 依赖以实现 BLAKE3 算法功能
- 新增 `hash/blake3` 包,提供多种 BLAKE3 哈希计算函数
  - 支持 BLAKE3、BLAKE3/224、BLAKE3/256、BLAKE3/384 等变种
  - 提供字节数组与文件的哈希计算及十六进制编码结果
- 更新 `go.mod` 和 `go.sum` 以包含新增依赖项
2025-10-07 22:38:43 +08:00
徐涛
357b19d9ad feat(hash): 添加 BLAKE2b 校验和算法支持
- 在 `hash` 模块中新增 `blake2b` 子包,实现 BLAKE2b 系列散列算法
- 支持多种输出长度:224、256、384 和 512 位
- 提供字节及十六进制字符串两种格式的散列计算函数
- 支持对字节数组和文件进行散列计算
- 更新 go.mod 使用 Go 1.24.0 并引入 golang.org/x/crypto 和 golang.org/x/sys 依赖
- 更新 README.md 标记 BLAKE2b 功能为已完成
2025-10-07 22:29:05 +08:00
徐涛
53330ceab9 docs(readme): 更新功能列表描述,明确算法封装类型
- 为散列及校验和算法项添加“便捷封装”说明
- 添加 BLAKE2 和 BLAKE3 算法项(未实现)
- 修正冰雹 ID 生成器描述格式
- 补充 UUIDv7 生成器的详细说明
2025-10-06 09:41:46 +08:00
徐涛
7ff09285dd feat(uuidv7): 完善 UUIDv7 功能并更新文档
- 实现 UUIDv7 生成、比较及排序功能
- 新增基于 Base36 和 Base64 的 UUIDv7 编码与解码方法
- 更新 README.md,标记相关功能为已完成状态
2025-10-06 09:27:30 +08:00
徐涛
39e8723dbd feat(uuidv7): 添加 UUIDv7 生成器及解析功能
新增 UUIDv7 生成器实现,支持基于时间戳、节点 ID 和序列号的唯一标识符生成。
包含初始化、生成、解析以及错误处理等相关逻辑,并提供字节和字符串两种形式的
序列化与反序列化方法。同时添加了对生成器未初始化和节点 ID 超限的错误定义。
2025-10-05 22:30:22 +08:00
徐涛
9952b2677c docs(README): 更新 Base36 算法功能状态为已完成
将 README.md 中的 Base36 算法功能状态从未完成 [ ] 更新为已完成 [x],
以准确反映当前项目功能的实现情况。
2025-10-05 09:41:49 +08:00
徐涛
fbc419f92e test(base36): 添加 Encode 和 EncodeInt64 的模糊测试
为 base36 包添加了两个 fuzz 测试函数,分别用于测试
Encode/Decode 和 EncodeInt64/DecodeToInt64 的正确性。
测试覆盖了字符串和 int64 类型的编码与解码过程,
确保在各种输入下功能的稳定性和正确性。
2025-10-05 09:36:43 +08:00
徐涛
0d486f5d01 (feat):增加Base36编解码功能,待测。 2025-10-03 16:46:45 +08:00
徐涛
66ccb82415 chore(roadmap):更新下一阶段开发工作方向。 2025-10-02 22:19:06 +08:00
徐涛
1dd98c25df enhance(hail):暴露Hail ID算法的类型,方便其他项目中放置于Context中。 2023-07-27 15:54:26 +08:00
徐涛
68f052ef00 enhance(spiral):调整螺旋加密算法的默认强度。 2023-07-18 16:18:18 +08:00
徐涛
811e056bb8 enhance(spiral):螺旋加密算法增加兼容旧式设计算法功能。 2023-07-18 16:07:35 +08:00
徐涛
1f99378655 refactor(crc):重构CRC系列算法中对于模式的定义,限制其取值。 2023-07-16 11:45:31 +08:00
徐涛
732c01e36c fix(hash):修正Sha256算法中出现的位数设置错误。 2023-07-16 11:21:30 +08:00
徐涛
185f1f3195 fix(des):修复DES加密时出现的密文字节数组长度不足的情况。 2023-07-15 11:56:27 +08:00
徐涛
5e284f320d feat(crypto):完成RSA加密算法功能。 2023-07-15 08:11:07 +08:00
徐涛
b004e952c4 feat(serial):完成冰雹ID生成算法功能支持。 2023-07-14 08:48:17 +08:00
徐涛
955d3a96f2 enhance(hash):包装散列算法中的错误提示。 2023-07-13 13:58:53 +08:00
徐涛
2e276ca33c enhance(crypto):包装AES算法中的错误提示。 2023-07-13 13:50:06 +08:00
徐涛
3df5dbfd36 enhance(crypto):包装DES算法中的错误提示。 2023-07-13 13:49:10 +08:00
徐涛
da4d1ebf3a enhance(crypto):包装3DES算法中的错误提示。 2023-07-13 13:47:07 +08:00
徐涛
14c5ff45cd feat(crypto):完成Spiral加密算法功能。 2023-07-13 13:44:12 +08:00
徐涛
c083d6e8e0 doc(crypto):补充当前项目状态。 2023-07-13 10:26:02 +08:00
徐涛
31198605fb feat(crypto):基本完成3DES加密算法功能。 2023-07-13 10:25:32 +08:00
28 changed files with 1477 additions and 109 deletions

View File

@@ -3,7 +3,7 @@
Golang 中可以使用的常用辅助功能工具箱。主要配备以下功能: Golang 中可以使用的常用辅助功能工具箱。主要配备以下功能:
- 加解密算法 - 加解密算法
- [ ] 螺旋随机密钥自解密算法 - [x] 螺旋随机密钥自解密算法
- [x] AES-CBC 便捷加解密算法 - [x] AES-CBC 便捷加解密算法
- [x] No Padding - [x] No Padding
- [x] ZerosPadding - [x] ZerosPadding
@@ -12,34 +12,41 @@ Golang 中可以使用的常用辅助功能工具箱。主要配备以下功能
- [x] No Padding - [x] No Padding
- [x] ZerosPadding - [x] ZerosPadding
- [x] Pkcs7Padding - [x] Pkcs7Padding
- [ ] 3DES-CBC 便捷加解密算法 - [x] 3DES-CBC 便捷加解密算法
- [ ] No Padding - [x] No Padding
- [ ] ZerosPadding - [x] ZerosPadding
- [ ] Pkcs7Padding - [x] Pkcs7Padding
- [ ] RSA 加解密算法 - [x] RSA 加解密算法
- [ ] 1024 位长 - [x] 1024 位长
- [ ] 2048 位长 - [x] 2048 位长
- [ ] KeyPair 生成器 - [x] KeyPair 生成器
- [ ] RSA 签名算法 - [x] Key 导入与导出
- 散列及校验和算法 - [x] RSA 签名算法
- [x] Sha512 散列算法 - 散列及校验和算法
- [x] Sha256 散列算法 - [x] Sha512 散列算法(便捷封装)
- [x] Sha1 散列算法 - [x] Sha256 散列算法(便捷封装)
- [x] MD5 散列算法 - [x] Sha1 散列算法(便捷封装)
- [x] CRC8 校验和算法 - [x] MD5 散列算法(便捷封装)
- [x] CRC16 校验和算法 - [x] CRC8 校验和算法(便捷封装)
- [x] CRC32 校验和算法 - [x] CRC16 校验和算法(便捷封装)
- [x] CRC64 校验和算法 - [x] CRC32 校验和算法(便捷封装)
- [x] pHash 图像感知算法 - [x] CRC64 校验和算法(便捷封装)
- [x] pHash 图像感知算法(便捷封装)
- [x] BLAKE2b 校验和算法(便捷封装)
- [x] BLAKE3 校验和算法(便捷封装)
- [ ] BlockHash 散列算法 - [ ] BlockHash 散列算法
- 唯一序列号生成器 - 唯一序列号生成器
- [ ] 冰雹 ID 生成器(短主机精简日期版雪花 ID) - [x] 冰雹 ID 生成器短主机精简日期版雪花 ID
- [x] UUID 生成器 - [x] UUIDv4 生成器
- [x] UUIDv7 生成器(自定义时间戳分布式版本)
- [x] UUIDv7 比较及排序
- [x] 基于 Base36 的 short UUIDv7 转换器
- [x] short UUID 生成器 - [x] short UUID 生成器
- 验证码生成器 - 验证码生成器
- [x] 随机验证码生成算法 - [x] 随机验证码生成算法
- 序列化算法 - 序列化算法
- [x] Base64 算法 - [x] Base64 算法
- [x] Base36 算法
- [x] Hex 直转 - [x] Hex 直转
- 常用工具函数 - 常用工具函数
- [ ] 日期时间函数 - [ ] 日期时间函数

View File

@@ -5,6 +5,7 @@ import (
"crypto/aes" "crypto/aes"
"crypto/cipher" "crypto/cipher"
"crypto/sha256" "crypto/sha256"
"fmt"
"archgrid.xyz/ag/toolsbox/encryption" "archgrid.xyz/ag/toolsbox/encryption"
) )
@@ -36,7 +37,7 @@ func Encrypt(data []byte, key []byte, padding encryption.PaddingMode, ivGenerato
keyBytes := generateKey(key) keyBytes := generateKey(key)
block, err := aes.NewCipher(keyBytes[:]) block, err := aes.NewCipher(keyBytes[:])
if err != nil { if err != nil {
return nil, err return nil, fmt.Errorf("创建加密单元失败,%w", err)
} }
iv := append(ivGenerator, XorIVGenerator)[0](keyBytes) iv := append(ivGenerator, XorIVGenerator)[0](keyBytes)
plainText := encryption.Padding(data, block.BlockSize(), padding) plainText := encryption.Padding(data, block.BlockSize(), padding)
@@ -54,7 +55,7 @@ func Decrypt(data []byte, key []byte, padding encryption.PaddingMode, ivGenerato
keyBytes := generateKey(key) keyBytes := generateKey(key)
block, err := aes.NewCipher(keyBytes[:]) block, err := aes.NewCipher(keyBytes[:])
if err != nil { if err != nil {
return nil, err return nil, fmt.Errorf("创建加密单元失败,%w", err)
} }
iv := append(ivGenerator, XorIVGenerator)[0](keyBytes) iv := append(ivGenerator, XorIVGenerator)[0](keyBytes)

View File

@@ -5,6 +5,7 @@ import (
"crypto/cipher" "crypto/cipher"
"crypto/des" "crypto/des"
"crypto/sha256" "crypto/sha256"
"fmt"
"archgrid.xyz/ag/toolsbox/encryption" "archgrid.xyz/ag/toolsbox/encryption"
) )
@@ -36,12 +37,12 @@ func Encrypt(data []byte, key []byte, padding encryption.PaddingMode, keyGenerat
keyBytes := append(keyGenerator, XorKeyGenerator)[0](key) keyBytes := append(keyGenerator, XorKeyGenerator)[0](key)
block, err := des.NewCipher(keyBytes[:]) block, err := des.NewCipher(keyBytes[:])
if err != nil { if err != nil {
return nil, err return nil, fmt.Errorf("创建加密单元失败,%w", err)
} }
iv := keyBytes[:] iv := keyBytes[:]
cipherText := make([]byte, len(data))
plainText := encryption.Padding(data, block.BlockSize(), padding) plainText := encryption.Padding(data, block.BlockSize(), padding)
cipherText := make([]byte, len(plainText))
mode := cipher.NewCBCEncrypter(block, iv) mode := cipher.NewCBCEncrypter(block, iv)
mode.CryptBlocks(cipherText, plainText) mode.CryptBlocks(cipherText, plainText)
@@ -55,7 +56,7 @@ func Decrypt(data []byte, key []byte, padding encryption.PaddingMode, keyGenerat
keyBytes := append(keyGenerator, XorKeyGenerator)[0](key) keyBytes := append(keyGenerator, XorKeyGenerator)[0](key)
block, err := des.NewCipher(keyBytes[:]) block, err := des.NewCipher(keyBytes[:])
if err != nil { if err != nil {
return nil, err return nil, fmt.Errorf("创建加密单元失败,%w", err)
} }
iv := keyBytes[:] iv := keyBytes[:]

View File

@@ -37,6 +37,9 @@ func Unpadding(data []byte, padding ...PaddingMode) []byte {
case PKCS7Padding: case PKCS7Padding:
length := len(data) length := len(data)
unpadding := int(data[length-1]) unpadding := int(data[length-1])
if length-unpadding < 0 {
return make([]byte, 0)
}
return data[:(length - unpadding)] return data[:(length - unpadding)]
case NoPadding: case NoPadding:
return data return data

67
encryption/rsa/errors.go Normal file
View File

@@ -0,0 +1,67 @@
package rsa
import "fmt"
type UnableToGenerateKeyPairError struct {
err error
}
func (e *UnableToGenerateKeyPairError) Error() string {
return fmt.Sprintf("未能生成密钥对, %s", e.err)
}
type AbsentPrivateKeyError struct{}
func (e *AbsentPrivateKeyError) Error() string {
return "缺少私钥"
}
type AbsentPublicKeyError struct{}
func (e *AbsentPublicKeyError) Error() string {
return "缺少公钥"
}
type EncryptionError struct {
err error
}
func (e *EncryptionError) Error() string {
return fmt.Sprintf("加密失败, %s", e.err)
}
type DecryptionError struct {
err error
}
func (e *DecryptionError) Error() string {
return fmt.Sprintf("解密失败, %s", e.err)
}
type KeyNotFoundError struct{}
func (e *KeyNotFoundError) Error() string {
return "找不到密钥"
}
type InvalidSignMethodError struct{}
func (e *InvalidSignMethodError) Error() string {
return "无效的签名方法"
}
type SignError struct {
err error
}
func (e *SignError) Error() string {
return fmt.Sprintf("签名失败, %s", e.err)
}
type VerifyError struct {
err error
}
func (e *VerifyError) Error() string {
return fmt.Sprintf("验证失败, %s", e.err)
}

141
encryption/rsa/key.go Normal file
View File

@@ -0,0 +1,141 @@
package rsa
import (
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
)
type KeyFormat int
const (
RSA KeyFormat = iota
COMMON
)
// 将指定的私钥编码为PEM格式如果不指定具体格式将使用RSA PRIVATE KEY(PKCS1)格式。
func EncodePrivateKey(key *rsa.PrivateKey, format ...KeyFormat) ([]byte, error) {
var block *pem.Block
switch append(format, RSA)[0] {
case COMMON:
key, err := x509.MarshalPKCS8PrivateKey(key)
if err != nil {
return nil, fmt.Errorf("不支持的私钥格式,%w", err)
}
block = &pem.Block{
Type: "PRIVATE KEY",
Bytes: key,
}
case RSA:
fallthrough
default:
key := x509.MarshalPKCS1PrivateKey(key)
block = &pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: key,
}
}
return pem.EncodeToMemory(block), nil
}
// 将指定的公钥编码为PEM格式如果不指定具体格式将使用RSA PUBLIC KEY(PKCS1)格式。
func EncodePublicKey(key *rsa.PublicKey, format ...KeyFormat) ([]byte, error) {
var block *pem.Block
switch append(format, RSA)[0] {
case COMMON:
key, err := x509.MarshalPKIXPublicKey(key)
if err != nil {
return nil, fmt.Errorf("不支持的公钥格式,%w", err)
}
block = &pem.Block{
Type: "PUBLIC KEY",
Bytes: key,
}
case RSA:
fallthrough
default:
key := x509.MarshalPKCS1PublicKey(key)
block = &pem.Block{
Type: "RSA PUBLIC KEY",
Bytes: key,
}
}
return pem.EncodeToMemory(block), nil
}
// 将给定的PEM证书内容解析为RSA私钥。
// 仅能读取PEM证书中的第一个私钥编码段。
func DecodePrivateKey(cert []byte) (*rsa.PrivateKey, error) {
var (
block *pem.Block
pemRestContent = cert
)
for {
block, pemRestContent = pem.Decode(pemRestContent)
if block == nil {
return nil, &KeyNotFoundError{}
}
if block.Type == "PRIVATE KEY" || block.Type == "RSA PRIVATE KEY" {
break
}
}
switch block.Type {
case "PRIVATE KEY":
key, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
return nil, fmt.Errorf("不支持的私钥格式,%w", err)
}
pKey, ok := key.(*rsa.PrivateKey)
if !ok {
return nil, fmt.Errorf("提供的私钥不是RSA专用私钥%w", err)
}
return pKey, nil
case "RSA PRIVATE KEY":
key, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return nil, fmt.Errorf("不支持的私钥格式,%w", err)
}
return key, nil
default:
return nil, fmt.Errorf("不支持的私钥格式或者私钥不存在,%s", block.Type)
}
}
// 将给定的PEM证书内容解析为RSA公钥。
// 仅能读取PEM证书中的第一个公钥编码段。
func DecodePublicKey(cert []byte) (*rsa.PublicKey, error) {
var (
block *pem.Block
pemRestContent = cert
)
for {
block, pemRestContent = pem.Decode(pemRestContent)
if block == nil {
return nil, &KeyNotFoundError{}
}
if block.Type == "PUBLIC KEY" || block.Type == "RSA PUBLIC KEY" {
break
}
}
switch block.Type {
case "PUBLIC KEY":
key, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return nil, fmt.Errorf("不支持的公钥格式,%w", err)
}
pKey, ok := key.(*rsa.PublicKey)
if !ok {
return nil, fmt.Errorf("提供的公钥不是RSA专用公钥%w", err)
}
return pKey, nil
case "RSA PUBLIC KEY":
key, err := x509.ParsePKCS1PublicKey(block.Bytes)
if err != nil {
return nil, fmt.Errorf("不支持的公钥格式,%w", err)
}
return key, nil
default:
return nil, fmt.Errorf("不支持的公钥格式或者公钥不存在,%s", block.Type)
}
}

181
encryption/rsa/rsa.go Normal file
View File

@@ -0,0 +1,181 @@
// 提供RSA不对称加解密功能。
package rsa
import (
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha512"
"errors"
)
type KeyLength int
type SignAlgorithm int
const (
RSA1024 KeyLength = 1024
RSA2048 KeyLength = 2048
)
const (
PSSSign SignAlgorithm = iota
PKCS1Sign
)
type KeyPair struct {
PublicKey *rsa.PublicKey
PrivateKey *rsa.PrivateKey
}
// 生成一个新的RSA密钥对。
func NewKeyPair(length KeyLength) (*KeyPair, error) {
privateKey, err := rsa.GenerateKey(rand.Reader, int(length))
if err != nil {
return nil, &UnableToGenerateKeyPairError{err: err}
}
publicKey := privateKey.Public().(*rsa.PublicKey)
return &KeyPair{
PublicKey: publicKey,
PrivateKey: privateKey,
}, nil
}
// 从一个PEM格式的密钥对中读取一套RSA密钥对。
// 如果获取到的公钥与私钥不配对,那么将自动使用私钥生成一个配对的公钥,以保证密钥对的完整性。
// 如果提供的证书中只存在公钥,那么将会保持私钥为空。
func NewFromPEM(cert []byte) (*KeyPair, error) {
publicKey, err := DecodePublicKey(cert)
if err != nil {
if errors.Is(err, &KeyNotFoundError{}) {
publicKey = nil
} else {
return nil, err
}
}
privateKey, err := DecodePrivateKey(cert)
if err != nil {
if errors.Is(err, &KeyNotFoundError{}) {
privateKey = nil
} else {
return nil, err
}
}
if privateKey != nil {
pubKeyFromPriKey := privateKey.Public().(*rsa.PublicKey)
if publicKey == nil || !publicKey.Equal(pubKeyFromPriKey) {
publicKey = pubKeyFromPriKey
}
}
return &KeyPair{
PublicKey: publicKey,
PrivateKey: privateKey,
}, nil
}
// 加载一个新的公钥,将会自动清空私钥。
func (kp *KeyPair) LoadPublicKey(cert []byte) error {
publicKey, err := DecodePublicKey(cert)
if err != nil {
return err
}
kp.PublicKey = publicKey
kp.PrivateKey = nil
return nil
}
// 加载一个私钥,将会自动生成一个配对的公钥。
func (kp *KeyPair) LoadPrivateKey(cert []byte) error {
privateKey, err := DecodePrivateKey(cert)
if err != nil {
return err
}
kp.PrivateKey = privateKey
kp.PublicKey = privateKey.Public().(*rsa.PublicKey)
return nil
}
// 使用密钥对加密给定的数据,如果密钥对中不存在公钥则会返回错误。
func (kp KeyPair) Encrypt(data []byte, label ...[]byte) ([]byte, error) {
if kp.PublicKey == nil {
return nil, &AbsentPublicKeyError{}
}
var cipherLabel []byte
if len(label) > 0 {
cipherLabel = label[0]
} else {
cipherLabel = nil
}
hasher := sha512.New()
cipherText, err := rsa.EncryptOAEP(hasher, rand.Reader, kp.PublicKey, data, cipherLabel)
if err != nil {
return nil, &EncryptionError{err: err}
}
return cipherText, nil
}
// 使用密钥对解密给定的数据,如果密钥对中不存在私钥则会返回错误。
func (kp KeyPair) Decrypt(data []byte, label ...[]byte) ([]byte, error) {
if kp.PrivateKey == nil {
return nil, &AbsentPrivateKeyError{}
}
var cipherLabel []byte
if len(label) > 0 {
cipherLabel = label[0]
} else {
cipherLabel = nil
}
hasher := sha512.New()
plainText, err := rsa.DecryptOAEP(hasher, rand.Reader, kp.PrivateKey, data, cipherLabel)
if err != nil {
return nil, &DecryptionError{err: err}
}
return plainText, nil
}
// 对给定的数据使用私钥进行签名。
func (kp KeyPair) Sign(data []byte, algorithm ...SignAlgorithm) ([]byte, error) {
if kp.PrivateKey == nil {
return nil, &AbsentPrivateKeyError{}
}
hashedData := sha512.Sum512(data)
switch append(algorithm, PSSSign)[0] {
case PSSSign:
signature, err := rsa.SignPSS(rand.Reader, kp.PrivateKey, crypto.SHA512, hashedData[:], &rsa.PSSOptions{SaltLength: 64})
if err != nil {
return nil, &SignError{err: err}
}
return signature, nil
case PKCS1Sign:
signature, err := rsa.SignPKCS1v15(rand.Reader, kp.PrivateKey, crypto.SHA512, hashedData[:])
if err != nil {
return nil, &SignError{err: err}
}
return signature, nil
default:
return nil, &InvalidSignMethodError{}
}
}
// 对给定的数据和签名数据使用公钥进行验证。不返回任何错误信息即表示验证成功。
func (kp KeyPair) Verify(data, signature []byte, algorithm ...SignAlgorithm) error {
if kp.PublicKey == nil {
return &AbsentPublicKeyError{}
}
hashedData := sha512.Sum512(data)
switch append(algorithm, PSSSign)[0] {
case PSSSign:
err := rsa.VerifyPSS(kp.PublicKey, crypto.SHA512, hashedData[:], signature, &rsa.PSSOptions{SaltLength: 64})
if err != nil {
return &VerifyError{err: err}
}
return nil
case PKCS1Sign:
err := rsa.VerifyPKCS1v15(kp.PublicKey, crypto.SHA512, hashedData[:], signature)
if err != nil {
return &VerifyError{err: err}
}
return nil
default:
return &InvalidSignMethodError{}
}
}

View File

@@ -0,0 +1,75 @@
// 提供自定义的随机密钥自解密加密算法支持算法代号Spiral。
package spiral
import (
"errors"
"fmt"
"strings"
"archgrid.xyz/ag/toolsbox/encryption"
"archgrid.xyz/ag/toolsbox/encryption/aes"
"archgrid.xyz/ag/toolsbox/hash/sha512"
verifyCode "archgrid.xyz/ag/toolsbox/random/verify_code"
"archgrid.xyz/ag/toolsbox/serialize/base64"
)
type Strength int
const (
Compatible Strength = iota
Enhanced
)
// 根据给定的密钥字符串生成加解密使用的密钥。
func generateKey(key string) []byte {
keyBytes := sha512.Sha512([]byte(key))
return keyBytes[4:36]
}
// 对给定的数据进行加密。
func Encrypt(data string, strength ...Strength) (string, error) {
var ivGen aes.IVGenerator
if append(strength, Enhanced)[0] == Compatible {
ivGen = aes.PrefixIVGenerator
} else {
ivGen = aes.XorIVGenerator
}
key := verifyCode.RandStr(20)
keyBytes := generateKey(key)
cipherData, err := aes.Encrypt([]byte(data), keyBytes, encryption.PKCS7Padding, ivGen)
if err != nil {
return "", fmt.Errorf("加密计算失败,%w", err)
}
var result strings.Builder
result.WriteString("[")
result.WriteString(key)
result.WriteString(base64.ToBase64(cipherData))
return result.String(), nil
}
// 对给定的数据进行解密。
func Decrypt(data string, strength ...Strength) (string, error) {
var ivGen aes.IVGenerator
if append(strength, Enhanced)[0] == Compatible {
ivGen = aes.PrefixIVGenerator
} else {
ivGen = aes.XorIVGenerator
}
if message, found := strings.CutPrefix(data, "["); found {
if len(message) > 20 {
keySeed := message[:20]
key := generateKey(keySeed)
cipherData, err := base64.FromBase64(message[20:])
if err != nil {
return "", fmt.Errorf("密文损坏无法解析,%w", err)
}
plainText, err := aes.Decrypt(cipherData, key, encryption.PKCS7Padding, ivGen)
if err != nil {
return "", fmt.Errorf("密文解密计算失败,%w", err)
}
return string(plainText), nil
}
return "", errors.New("密文缺损,无法完成解密。")
}
return data, nil
}

102
encryption/tdes/tdes.go Normal file
View File

@@ -0,0 +1,102 @@
// 提供3DES-EDE加解密算法本解密算法采用`(K1, K2, K3)`的安全长密钥。
package tdes
import (
"crypto/cipher"
"crypto/des"
"crypto/sha256"
"fmt"
"archgrid.xyz/ag/toolsbox/encryption"
)
type KeyGenerator func([]byte) [3][8]byte
// 直接采用分组的方式将密钥分为4个部分取前三个部分作为3DES的密钥。
func PartitionKeyGenerator(key []byte) [3][8]byte {
hashedKey := sha256.Sum256(key)
return [3][8]byte{
([8]byte)(hashedKey[0:8]),
([8]byte)(hashedKey[8:16]),
([8]byte)(hashedKey[16:24]),
}
}
// 对给定密钥进行Sha256散列以后将散列结果分为三部分分别作为3DES的密钥前三组分别与第四组异或得到3组新的密钥。
func XorKeyGenerator(key []byte) [3][8]byte {
hashedKey := sha256.Sum256(key)
var result [3][8]byte
for i := 0; i < 3; i++ {
for j := 0; j < 8; j++ {
result[i][j] = hashedKey[i*8+j] ^ hashedKey[3*8+j]
}
}
return result
}
// 对给定的数据使用给定的密钥进行加密。IV与密钥相同。
func rawDesEncrypt(data []byte, key [8]byte) ([]byte, error) {
block, err := des.NewCipher(key[:])
if err != nil {
return nil, fmt.Errorf("创建加密单元失败,%w", err)
}
iv := key[:]
cipherText := make([]byte, len(data))
mode := cipher.NewCBCEncrypter(block, iv)
mode.CryptBlocks(cipherText, data)
return cipherText, nil
}
// 对给定的数据使用给定的密钥进行解密。IV与密钥相同。
func rawDesDecrypt(data []byte, key [8]byte) ([]byte, error) {
block, err := des.NewCipher(key[:])
if err != nil {
return nil, fmt.Errorf("创建加密单元失败,%w", err)
}
iv := key[:]
plainText := make([]byte, len(data))
mode := cipher.NewCBCDecrypter(block, iv)
mode.CryptBlocks(plainText, data)
return plainText, nil
}
// 对给定的数据进行加密。
// 3DES-EDE加密IV为8字节默认与运算后的密钥相同。
// 参数padding指定了填充方式可选值为NoPadding、ZeroPadding和PKCS7Padding默认采用ZeroPadding。
func Encrypt(data []byte, key []byte, padding encryption.PaddingMode, keyGenerator ...KeyGenerator) ([]byte, error) {
desKeys := append(keyGenerator, XorKeyGenerator)[0](key)
plainText := encryption.Padding(data, des.BlockSize, padding)
cipher1Text, err := rawDesEncrypt(plainText, desKeys[0])
if err != nil {
return nil, fmt.Errorf("第一阶段加密失败,%w", err)
}
plain2Text, err := rawDesDecrypt(cipher1Text, desKeys[1])
if err != nil {
return nil, fmt.Errorf("第二阶段解密失败,%w", err)
}
cipher3Text, err := rawDesEncrypt(plain2Text, desKeys[2])
if err != nil {
return nil, fmt.Errorf("第三阶段加密失败,%w", err)
}
return cipher3Text, nil
}
// 对给定的数据进行解密。
// 3DES-EDE解密IV为8字节默认与运算后的密钥相同。
// 参数padding指定了填充方式可选值为NoPadding、ZeroPadding和PKCS7Padding默认采用ZeroPadding。
func Decrypt(data []byte, key []byte, padding encryption.PaddingMode, keyGenerator ...KeyGenerator) ([]byte, error) {
desKeys := append(keyGenerator, XorKeyGenerator)[0](key)
plainText, err := rawDesDecrypt(data, desKeys[2])
if err != nil {
return nil, fmt.Errorf("第三阶段解密失败,%w", err)
}
cipher2Text, err := rawDesEncrypt(plainText, desKeys[1])
if err != nil {
return nil, fmt.Errorf("第二阶段加密失败,%w", err)
}
plain3Text, err := rawDesDecrypt(cipher2Text, desKeys[0])
if err != nil {
return nil, fmt.Errorf("第一阶段解密失败,%w", err)
}
return encryption.Unpadding(plain3Text, des.BlockSize, padding), nil
}

6
go.mod
View File

@@ -1,13 +1,15 @@
module archgrid.xyz/ag/toolsbox module archgrid.xyz/ag/toolsbox
go 1.20 go 1.24.0
require go.uber.org/zap v1.24.0 require go.uber.org/zap v1.24.0
require ( require (
github.com/azr/gift v1.1.2 // indirect github.com/azr/gift v1.1.2 // indirect
github.com/disintegration/imaging v1.6.2 // indirect github.com/disintegration/imaging v1.6.2 // indirect
github.com/klauspost/cpuid/v2 v2.0.9 // indirect
golang.org/x/image v0.0.0-20220722155232-062f8c9fd539 // indirect golang.org/x/image v0.0.0-20220722155232-062f8c9fd539 // indirect
golang.org/x/sys v0.36.0 // indirect
) )
require ( require (
@@ -17,4 +19,6 @@ require (
github.com/sigurn/crc8 v0.0.0-20220107193325-2243fe600f9f github.com/sigurn/crc8 v0.0.0-20220107193325-2243fe600f9f
go.uber.org/atomic v1.7.0 // indirect go.uber.org/atomic v1.7.0 // indirect
go.uber.org/multierr v1.6.0 // indirect go.uber.org/multierr v1.6.0 // indirect
golang.org/x/crypto v0.42.0
lukechampine.com/blake3 v1.4.1
) )

8
go.sum
View File

@@ -10,6 +10,8 @@ github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/howeyc/crc16 v0.0.0-20171223171357-2b2a61e366a6 h1:IIVxLyDUYErC950b8kecjoqDet8P5S4lcVRUOM6rdkU= github.com/howeyc/crc16 v0.0.0-20171223171357-2b2a61e366a6 h1:IIVxLyDUYErC950b8kecjoqDet8P5S4lcVRUOM6rdkU=
github.com/howeyc/crc16 v0.0.0-20171223171357-2b2a61e366a6/go.mod h1:JslaLRrzGsOKJgFEPBP65Whn+rdwDQSk0I0MCRFe2Zw= github.com/howeyc/crc16 v0.0.0-20171223171357-2b2a61e366a6/go.mod h1:JslaLRrzGsOKJgFEPBP65Whn+rdwDQSk0I0MCRFe2Zw=
github.com/klauspost/cpuid/v2 v2.0.9 h1:lgaqFMSdTdQYdZ04uHyN2d/eKdOMyi2YLSvlQIBFYa4=
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/sigurn/crc8 v0.0.0-20220107193325-2243fe600f9f h1:1R9KdKjCNSd7F8iGTxIpoID9prlYH8nuNYKt0XvweHA= github.com/sigurn/crc8 v0.0.0-20220107193325-2243fe600f9f h1:1R9KdKjCNSd7F8iGTxIpoID9prlYH8nuNYKt0XvweHA=
github.com/sigurn/crc8 v0.0.0-20220107193325-2243fe600f9f/go.mod h1:vQhwQ4meQEDfahT5kd61wLAF5AAeh5ZPLVI4JJ/tYo8= github.com/sigurn/crc8 v0.0.0-20220107193325-2243fe600f9f/go.mod h1:vQhwQ4meQEDfahT5kd61wLAF5AAeh5ZPLVI4JJ/tYo8=
@@ -21,9 +23,15 @@ go.uber.org/multierr v1.6.0 h1:y6IPFStTAIT5Ytl7/XYmHvzXQ7S3g/IeZW9hyZ5thw4=
go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU= go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU=
go.uber.org/zap v1.24.0 h1:FiJd5l1UOLj0wCgbSE0rwwXHzEdAZS6hiiSnxJN/D60= go.uber.org/zap v1.24.0 h1:FiJd5l1UOLj0wCgbSE0rwwXHzEdAZS6hiiSnxJN/D60=
go.uber.org/zap v1.24.0/go.mod h1:2kMP+WWQ8aoFoedH3T2sq6iJ2yDWpHbP0f6MQbS9Gkg= go.uber.org/zap v1.24.0/go.mod h1:2kMP+WWQ8aoFoedH3T2sq6iJ2yDWpHbP0f6MQbS9Gkg=
golang.org/x/crypto v0.42.0 h1:chiH31gIWm57EkTXpwnqf8qeuMUi0yekh6mT2AvFlqI=
golang.org/x/crypto v0.42.0/go.mod h1:4+rDnOTJhQCx2q7/j6rAN5XDw8kPjeaXEUR2eL94ix8=
golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/image v0.0.0-20220722155232-062f8c9fd539 h1:/eM0PCrQI2xd471rI+snWuu251/+/jpBpZqir2mPdnU= golang.org/x/image v0.0.0-20220722155232-062f8c9fd539 h1:/eM0PCrQI2xd471rI+snWuu251/+/jpBpZqir2mPdnU=
golang.org/x/image v0.0.0-20220722155232-062f8c9fd539/go.mod h1:doUCurBvlfPMKfmIpRIywoHmhN3VyhnoFDbvIEWF4hY= golang.org/x/image v0.0.0-20220722155232-062f8c9fd539/go.mod h1:doUCurBvlfPMKfmIpRIywoHmhN3VyhnoFDbvIEWF4hY=
golang.org/x/sys v0.36.0 h1:KVRy2GtZBrk1cBYA7MKu5bEZFxQk4NIDV6RLVcC8o0k=
golang.org/x/sys v0.36.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
lukechampine.com/blake3 v1.4.1 h1:I3Smz7gso8w4/TunLKec6K2fn+kyKtDxr/xcQEN84Wg=
lukechampine.com/blake3 v1.4.1/go.mod h1:QFosUxmjB8mnrWFSNwKmvxHpfY72bmD2tQ0kBMM3kwo=

117
hash/blake2b/blake2b.go Normal file
View File

@@ -0,0 +1,117 @@
// 提供Blake2B系列散列算法函数和校验和函数。
package blake2b
import (
"encoding/hex"
"fmt"
"hash"
"io"
"os"
"golang.org/x/crypto/blake2b"
)
// 根据给定的位数返回一个散列算法的Hash实例。
func hasherSelect(bitSize int) hash.Hash {
switch bitSize {
case 224:
hasher, _ := blake2b.New256(nil)
return hasher
case 256:
hasher, _ := blake2b.New256(nil)
return hasher
case 384:
hasher, _ := blake2b.New384(nil)
return hasher
case 512:
hasher, _ := blake2b.New512(nil)
return hasher
default:
hasher, _ := blake2b.New256(nil)
return hasher
}
}
// 计算给定字节数组的Blake2B校验和返回字节数组。
func Blake2b(data []byte) []byte {
hasher := hasherSelect(512)
hasher.Write(data)
return hasher.Sum(nil)
}
// 计算给定字节数组的Blake2B/256校验和返回字节数组。
func Blake2b_256(data []byte) []byte {
hasher := hasherSelect(256)
hasher.Write(data)
return hasher.Sum(nil)
}
// 计算给定字节数组的Blake2B/384校验和返回字节数组。
func Blake2b_384(data []byte) []byte {
hasher := hasherSelect(384)
hasher.Write(data)
return hasher.Sum(nil)
}
// 计算给定字节数组的Blake2B/224校验和返回字节数组。
func Blake2b_224(data []byte) []byte {
hasher := hasherSelect(224)
hasher.Write(data)
return hasher.Sum(nil)
}
// 计算给定字节数组的Blake2B校验和返回十六进制字符串。
func Blake2bHex(data []byte) string {
return hex.EncodeToString(Blake2b(data))
}
// 计算给定字节数组的Blake2B/256校验和返回十六进制字符串。
func Blake2b_256Hex(data []byte) string {
return hex.EncodeToString(Blake2b_256(data))
}
// 计算给定字节数组的Blake2B/384校验和返回十六进制字符串。
func Blake2b_384Hex(data []byte) string {
return hex.EncodeToString(Blake2b_384(data))
}
// 计算给定字节数组的Blake2B/224校验和返回十六进制字符串。
func Blake2b_224Hex(data []byte) string {
return hex.EncodeToString(Blake2b_224(data))
}
// 根据给定位数计算一个字节数组的Blake2B校验和返回字节数组。
func Sum(data []byte, bitSize ...int) []byte {
hasher := hasherSelect(append(bitSize, 512)[0])
hasher.Write(data)
return hasher.Sum(nil)
}
// 根据给定位数计算一个字节数组的Blake2B校验和返回十六进制字符串。
func SumHex(data []byte, bitSize ...int) string {
return hex.EncodeToString(Sum(data, bitSize...))
}
// 根据给定位数计算一个文件的Blake2B校验和返回字节数组。
func SumFile(file string, bitSize ...int) ([]byte, error) {
f, err := os.Open(file)
if err != nil {
return nil, fmt.Errorf("未能打开指定文件,%w", err)
}
defer f.Close()
hasher := hasherSelect(append(bitSize, 512)[0])
if _, err := io.Copy(hasher, f); err != nil {
return nil, fmt.Errorf("未能读取指定文件的内容,%w", err)
}
return hasher.Sum(nil), nil
}
// 根据给定位数计算一个文件的Blake2B校验和返回十六进制字符串。
func SumFileHex(file string, bitSize ...int) (string, error) {
hash, err := SumFile(file, bitSize...)
if err != nil {
return "", err
}
return hex.EncodeToString(hash), nil
}

112
hash/blake3/blake3.go Normal file
View File

@@ -0,0 +1,112 @@
// 提供Blake3系列散列算法函数和校验和函数。
package blake3
import (
"encoding/hex"
"fmt"
"hash"
"io"
"os"
"lukechampine.com/blake3"
)
// 根据给定的位数返回一个散列算法的Hash实例。
func hasherSelect(bitSize int) hash.Hash {
switch bitSize {
case 224:
return blake3.New(28, nil)
case 256:
return blake3.New(32, nil)
case 384:
return blake3.New(48, nil)
case 512:
return blake3.New(64, nil)
default:
return blake3.New(32, nil)
}
}
// 计算给定字节数组的Blake3校验和返回字节数组。
func Blake3(data []byte) []byte {
hasher := hasherSelect(512)
hasher.Write(data)
return hasher.Sum(nil)
}
// 计算给定字节数组的Blake3/256校验和返回字节数组。
func Blake3_256(data []byte) []byte {
hasher := hasherSelect(256)
hasher.Write(data)
return hasher.Sum(nil)
}
// 计算给定字节数组的Blake3/384校验和返回字节数组。
func Blake3_384(data []byte) []byte {
hasher := hasherSelect(384)
hasher.Write(data)
return hasher.Sum(nil)
}
// 计算给定字节数组的Blake3/224校验和返回字节数组。
func Blake3_224(data []byte) []byte {
hasher := hasherSelect(224)
hasher.Write(data)
return hasher.Sum(nil)
}
// 计算给定字节数组的Blake3校验和返回十六进制字符串。
func Blake3Hex(data []byte) string {
return hex.EncodeToString(Blake3(data))
}
// 计算给定字节数组的Blake3/256校验和返回十六进制字符串。
func Blake3_256Hex(data []byte) string {
return hex.EncodeToString(Blake3_256(data))
}
// 计算给定字节数组的Blake3/384校验和返回十六进制字符串。
func Blake3_384Hex(data []byte) string {
return hex.EncodeToString(Blake3_384(data))
}
// 计算给定字节数组的Blake3/224校验和返回十六进制字符串。
func Blake3_224Hex(data []byte) string {
return hex.EncodeToString(Blake3_224(data))
}
// 根据给定位数计算一个字节数组的Blake3校验和返回字节数组。
func Sum(data []byte, bitSize ...int) []byte {
hasher := hasherSelect(append(bitSize, 512)[0])
hasher.Write(data)
return hasher.Sum(nil)
}
// 根据给定位数计算一个字节数组的Blake3校验和返回十六进制字符串。
func SumHex(data []byte, bitSize ...int) string {
return hex.EncodeToString(Sum(data, bitSize...))
}
// 根据给定位数计算一个文件的Blake3校验和返回字节数组。
func SumFile(file string, bitSize ...int) ([]byte, error) {
f, err := os.Open(file)
if err != nil {
return nil, fmt.Errorf("未能打开指定文件,%w", err)
}
defer f.Close()
hasher := hasherSelect(append(bitSize, 512)[0])
if _, err := io.Copy(hasher, f); err != nil {
return nil, fmt.Errorf("未能读取指定文件的内容,%w", err)
}
return hasher.Sum(nil), nil
}
// 根据给定位数计算一个文件的Blake3校验和返回十六进制字符串。
func SumFileHex(file string, bitSize ...int) (string, error) {
hash, err := SumFile(file, bitSize...)
if err != nil {
return "", err
}
return hex.EncodeToString(hash), nil
}

View File

@@ -3,24 +3,35 @@ package crc16
import ( import (
"encoding/hex" "encoding/hex"
"fmt"
"io" "io"
"os" "os"
"github.com/howeyc/crc16" "github.com/howeyc/crc16"
) )
type CRC16Mode int
const (
CCITT CRC16Mode = iota
CCITT_FALSE
SCSI
IBM
MBUS
)
// 根据给定的校验表类型生成对应的校验器 // 根据给定的校验表类型生成对应的校验器
func hasherSelect(table string) crc16.Hash16 { func hasherSelect(mdoe CRC16Mode) crc16.Hash16 {
switch table { switch mdoe {
case "CCITT": case CCITT:
return crc16.NewCCITT() return crc16.NewCCITT()
case "CCITT-FALSE": case CCITT_FALSE:
return crc16.New(crc16.MakeTable(crc16.CCITTFalse)) return crc16.New(crc16.MakeTable(crc16.CCITTFalse))
case "SCSI": case SCSI:
return crc16.NewSCSI() return crc16.NewSCSI()
case "IBM": case IBM:
return crc16.NewIBM() return crc16.NewIBM()
case "MBUS": case MBUS:
return crc16.New(crc16.MakeTable(crc16.MBUS)) return crc16.New(crc16.MakeTable(crc16.MBUS))
default: default:
return crc16.NewIBM() return crc16.NewIBM()
@@ -28,37 +39,37 @@ func hasherSelect(table string) crc16.Hash16 {
} }
// 计算给定字节数组的CRC16校验和返回字节数组 // 计算给定字节数组的CRC16校验和返回字节数组
func CRC16(data []byte, table ...string) []byte { func CRC16(data []byte, mode ...CRC16Mode) []byte {
crcTable := append(table, "IBM") crcTable := append(mode, IBM)
hasher := hasherSelect(crcTable[0]) hasher := hasherSelect(crcTable[0])
hasher.Write(data) hasher.Write(data)
return hasher.Sum(nil) return hasher.Sum(nil)
} }
// 计算给定字节数组的CRC16校验和返回十六进制字符串 // 计算给定字节数组的CRC16校验和返回十六进制字符串
func CRC16Hex(data []byte, table ...string) string { func CRC16Hex(data []byte, mode ...CRC16Mode) string {
return hex.EncodeToString(CRC16(data, table...)) return hex.EncodeToString(CRC16(data, mode...))
} }
// 计算指定文件的CRC16校验和返回字节数组 // 计算指定文件的CRC16校验和返回字节数组
func SumFile(file string, table ...string) ([]byte, error) { func SumFile(file string, mode ...CRC16Mode) ([]byte, error) {
f, err := os.Open(file) f, err := os.Open(file)
if err != nil { if err != nil {
return nil, err return nil, fmt.Errorf("未能打开指定文件,%w", err)
} }
defer f.Close() defer f.Close()
crcTable := append(table, "IBM") crcTable := append(mode, IBM)
hasher := hasherSelect(crcTable[0]) hasher := hasherSelect(crcTable[0])
if _, err := io.Copy(hasher, f); err != nil { if _, err := io.Copy(hasher, f); err != nil {
return nil, err return nil, fmt.Errorf("未能读取指定文件的内容,%w", err)
} }
return hasher.Sum(nil), nil return hasher.Sum(nil), nil
} }
// 计算指定文件的CRC16校验和返回十六进制字符串 // 计算指定文件的CRC16校验和返回十六进制字符串
func SumFileHex(file string, table ...string) (string, error) { func SumFileHex(file string, mode ...CRC16Mode) (string, error) {
hash, err := SumFile(file, table...) hash, err := SumFile(file, mode...)
if err != nil { if err != nil {
return "", err return "", err
} }

View File

@@ -3,19 +3,28 @@ package crc32
import ( import (
"encoding/hex" "encoding/hex"
"fmt"
"hash/crc32" "hash/crc32"
"io" "io"
"os" "os"
) )
type CRC32Mode int
const (
IEEE CRC32Mode = iota
Castagnoli
Koopman
)
// 选择一个CRC32校验表 // 选择一个CRC32校验表
func tableSelect(table string) *crc32.Table { func tableSelect(mode CRC32Mode) *crc32.Table {
switch table { switch mode {
case "IEEE": case IEEE:
return crc32.IEEETable return crc32.IEEETable
case "Castagnoli": case Castagnoli:
return crc32.MakeTable(crc32.Castagnoli) return crc32.MakeTable(crc32.Castagnoli)
case "Koopman": case Koopman:
return crc32.MakeTable(crc32.Koopman) return crc32.MakeTable(crc32.Koopman)
default: default:
return crc32.IEEETable return crc32.IEEETable
@@ -23,37 +32,37 @@ func tableSelect(table string) *crc32.Table {
} }
// 计算给定字节数组的CRC32校验和返回字节数组 // 计算给定字节数组的CRC32校验和返回字节数组
func CRC32(data []byte, table ...string) []byte { func CRC32(data []byte, mode ...CRC32Mode) []byte {
crcTable := append(table, "IEEE") crcTable := append(mode, IEEE)
hasher := crc32.New(tableSelect(crcTable[0])) hasher := crc32.New(tableSelect(crcTable[0]))
hasher.Write(data) hasher.Write(data)
return hasher.Sum(nil) return hasher.Sum(nil)
} }
// 计算给定字节数组的CRC32校验和返回十六进制字符串 // 计算给定字节数组的CRC32校验和返回十六进制字符串
func CRC32Hex(data []byte, table ...string) string { func CRC32Hex(data []byte, mode ...CRC32Mode) string {
return hex.EncodeToString(CRC32(data, table...)) return hex.EncodeToString(CRC32(data, mode...))
} }
// 计算指定文件的CRC32校验和返回字节数组 // 计算指定文件的CRC32校验和返回字节数组
func SumFile(file string, table ...string) ([]byte, error) { func SumFile(file string, mode ...CRC32Mode) ([]byte, error) {
f, err := os.Open(file) f, err := os.Open(file)
if err != nil { if err != nil {
return nil, err return nil, fmt.Errorf("未能打开指定文件,%w", err)
} }
defer f.Close() defer f.Close()
crcTable := append(table, "IEEE") crcTable := append(mode, IEEE)
hasher := crc32.New(tableSelect(crcTable[0])) hasher := crc32.New(tableSelect(crcTable[0]))
if _, err := io.Copy(hasher, f); err != nil { if _, err := io.Copy(hasher, f); err != nil {
return nil, err return nil, fmt.Errorf("未能读取指定文件的内容,%w", err)
} }
return hasher.Sum(nil), nil return hasher.Sum(nil), nil
} }
// 计算指定文件的CRC32校验和返回十六进制字符串 // 计算指定文件的CRC32校验和返回十六进制字符串
func SumFileHex(file string, table ...string) (string, error) { func SumFileHex(file string, mode ...CRC32Mode) (string, error) {
hash, err := SumFile(file, table...) hash, err := SumFile(file, mode...)
if err != nil { if err != nil {
return "", err return "", err
} }

View File

@@ -3,17 +3,25 @@ package crc64
import ( import (
"encoding/hex" "encoding/hex"
"fmt"
"hash/crc64" "hash/crc64"
"io" "io"
"os" "os"
) )
type CRC64Mode int
const (
ECMA CRC64Mode = iota
ISO
)
// 选择一个CRC64校验表。 // 选择一个CRC64校验表。
func tableSelect(table string) *crc64.Table { func tableSelect(mode CRC64Mode) *crc64.Table {
switch table { switch mode {
case "ECMA": case ECMA:
return crc64.MakeTable(crc64.ECMA) return crc64.MakeTable(crc64.ECMA)
case "ISO": case ISO:
return crc64.MakeTable(crc64.ISO) return crc64.MakeTable(crc64.ISO)
default: default:
return crc64.MakeTable(crc64.ISO) return crc64.MakeTable(crc64.ISO)
@@ -21,37 +29,37 @@ func tableSelect(table string) *crc64.Table {
} }
// 计算给定字节数组的CRC64校验和返回字节数组。 // 计算给定字节数组的CRC64校验和返回字节数组。
func CRC64(data []byte, table ...string) []byte { func CRC64(data []byte, mode ...CRC64Mode) []byte {
crcTable := append(table, "ISO") crcTable := append(mode, ISO)
hasher := crc64.New(tableSelect(crcTable[0])) hasher := crc64.New(tableSelect(crcTable[0]))
hasher.Write(data) hasher.Write(data)
return hasher.Sum(nil) return hasher.Sum(nil)
} }
// 计算给定字节数组的CRC64校验和返回十六进制字符串。 // 计算给定字节数组的CRC64校验和返回十六进制字符串。
func CRC64Hex(data []byte, table ...string) string { func CRC64Hex(data []byte, mode ...CRC64Mode) string {
return hex.EncodeToString(CRC64(data, table...)) return hex.EncodeToString(CRC64(data, mode...))
} }
// 计算一个指定文件的CRC64校验和返回字节数组。 // 计算一个指定文件的CRC64校验和返回字节数组。
func SumFile(file string, table ...string) ([]byte, error) { func SumFile(file string, mode ...CRC64Mode) ([]byte, error) {
f, err := os.Open(file) f, err := os.Open(file)
if err != nil { if err != nil {
return nil, err return nil, fmt.Errorf("未能打开指定文件,%w", err)
} }
defer f.Close() defer f.Close()
crcTable := append(table, "ISO") crcTable := append(mode, ISO)
hasher := crc64.New(tableSelect(crcTable[0])) hasher := crc64.New(tableSelect(crcTable[0]))
if _, err := io.Copy(hasher, f); err != nil { if _, err := io.Copy(hasher, f); err != nil {
return nil, err return nil, fmt.Errorf("未能读取指定文件的内容,%w", err)
} }
return hasher.Sum(nil), nil return hasher.Sum(nil), nil
} }
// 计算一个指定文件的CRC64校验和返回十六进制字符串。 // 计算一个指定文件的CRC64校验和返回十六进制字符串。
func SumFileHex(file string, table ...string) (string, error) { func SumFileHex(file string, mode ...CRC64Mode) (string, error) {
hash, err := SumFile(file, table...) hash, err := SumFile(file, mode...)
if err != nil { if err != nil {
return "", err return "", err
} }

View File

@@ -3,33 +3,49 @@ package crc8
import ( import (
"encoding/hex" "encoding/hex"
"fmt"
"os" "os"
"github.com/sigurn/crc8" "github.com/sigurn/crc8"
) )
type CRC8Mode int
const (
ORIGIN CRC8Mode = iota
CDMA2000
DARC
DVB_S2
EBU
I_CODE
ITU
MAXIM
ROHC
WCDMA
)
// 根据提供的校验表名称生成对应的校验表 // 根据提供的校验表名称生成对应的校验表
func hasherSelect(table string) *crc8.Table { func hasherSelect(mode CRC8Mode) *crc8.Table {
switch table { switch mode {
case "CRC8": case ORIGIN:
return crc8.MakeTable(crc8.CRC8) return crc8.MakeTable(crc8.CRC8)
case "CDMA2000": case CDMA2000:
return crc8.MakeTable(crc8.CRC8_CDMA2000) return crc8.MakeTable(crc8.CRC8_CDMA2000)
case "DARC": case DARC:
return crc8.MakeTable(crc8.CRC8_DARC) return crc8.MakeTable(crc8.CRC8_DARC)
case "DVB-S2": case DVB_S2:
return crc8.MakeTable(crc8.CRC8_DVB_S2) return crc8.MakeTable(crc8.CRC8_DVB_S2)
case "EBU": case EBU:
return crc8.MakeTable(crc8.CRC8_EBU) return crc8.MakeTable(crc8.CRC8_EBU)
case "I-CODE": case I_CODE:
return crc8.MakeTable(crc8.CRC8_I_CODE) return crc8.MakeTable(crc8.CRC8_I_CODE)
case "ITU": case ITU:
return crc8.MakeTable(crc8.CRC8_ITU) return crc8.MakeTable(crc8.CRC8_ITU)
case "MAXIM": case MAXIM:
return crc8.MakeTable(crc8.CRC8_MAXIM) return crc8.MakeTable(crc8.CRC8_MAXIM)
case "ROHC": case ROHC:
return crc8.MakeTable(crc8.CRC8_ROHC) return crc8.MakeTable(crc8.CRC8_ROHC)
case "WCDMA": case WCDMA:
return crc8.MakeTable(crc8.CRC8_WCDMA) return crc8.MakeTable(crc8.CRC8_WCDMA)
default: default:
return crc8.MakeTable(crc8.CRC8) return crc8.MakeTable(crc8.CRC8)
@@ -37,35 +53,35 @@ func hasherSelect(table string) *crc8.Table {
} }
// 计算给定字节数组的CRC8校验和返回字节数组 // 计算给定字节数组的CRC8校验和返回字节数组
func CRC8(data []byte, table ...string) []byte { func CRC8(data []byte, mode ...CRC8Mode) []byte {
crcTable := append(table, "CRC8") crcTable := append(mode, ORIGIN)
return []byte{crc8.Checksum(data, hasherSelect(crcTable[0]))} return []byte{crc8.Checksum(data, hasherSelect(crcTable[0]))}
} }
// 计算给定字节数组的CRC8校验和返回十六进制字符串 // 计算给定字节数组的CRC8校验和返回十六进制字符串
func CRC8Hex(data []byte, table ...string) string { func CRC8Hex(data []byte, mode ...CRC8Mode) string {
return hex.EncodeToString(CRC8(data, table...)) return hex.EncodeToString(CRC8(data, mode...))
} }
// 计算指定文件的CRC8校验和返回字节数组 // 计算指定文件的CRC8校验和返回字节数组
func SumFile(file string, table ...string) ([]byte, error) { func SumFile(file string, mode ...CRC8Mode) ([]byte, error) {
f, err := os.Open(file) f, err := os.Open(file)
if err != nil { if err != nil {
return nil, err return nil, fmt.Errorf("未能打开指定文件,%w", err)
} }
defer f.Close() defer f.Close()
crcTable := append(table, "CRC8") crcTable := append(mode, ORIGIN)
var buf = make([]byte, 0) var buf = make([]byte, 0)
if _, err := f.Read(buf); err != nil { if _, err := f.Read(buf); err != nil {
return nil, err return nil, fmt.Errorf("读取指定文件内容出错,%w", err)
} }
return []byte{crc8.Checksum(buf, hasherSelect(crcTable[0]))}, nil return []byte{crc8.Checksum(buf, hasherSelect(crcTable[0]))}, nil
} }
// 计算指定文件的CRC8校验和返回十六进制字符串 // 计算指定文件的CRC8校验和返回十六进制字符串
func SumFileHex(file string, table ...string) (string, error) { func SumFileHex(file string, mode ...CRC8Mode) (string, error) {
crc, err := SumFile(file, table...) crc, err := SumFile(file, mode...)
if err != nil { if err != nil {
return "", err return "", err
} }

View File

@@ -4,6 +4,7 @@ package md5
import ( import (
"crypto/md5" "crypto/md5"
"encoding/hex" "encoding/hex"
"fmt"
"io" "io"
"os" "os"
) )
@@ -24,13 +25,13 @@ func MD5Hex(data []byte) string {
func SumFile(file string) ([]byte, error) { func SumFile(file string) ([]byte, error) {
f, err := os.Open(file) f, err := os.Open(file)
if err != nil { if err != nil {
return nil, err return nil, fmt.Errorf("未能打开指定文件,%w", err)
} }
defer f.Close() defer f.Close()
hasher := md5.New() hasher := md5.New()
if _, err := io.Copy(hasher, f); err != nil { if _, err := io.Copy(hasher, f); err != nil {
return nil, err return nil, fmt.Errorf("未能读取指定文件的内容,%w", err)
} }
return hasher.Sum(nil), nil return hasher.Sum(nil), nil
} }

View File

@@ -4,6 +4,7 @@ package phash
import ( import (
"encoding/binary" "encoding/binary"
"encoding/hex" "encoding/hex"
"fmt"
"image" "image"
"os" "os"
@@ -27,13 +28,13 @@ func HashHex(image image.Image) string {
func HashFile(file string) ([]byte, error) { func HashFile(file string) ([]byte, error) {
f, err := os.Open(file) f, err := os.Open(file)
if err != nil { if err != nil {
return nil, err return nil, fmt.Errorf("未能打开指定文件,%w", err)
} }
defer f.Close() defer f.Close()
img, _, err := image.Decode(f) img, _, err := image.Decode(f)
if err != nil { if err != nil {
return nil, err return nil, fmt.Errorf("未能解码指定图像文件,%w", err)
} }
return Hash(img), nil return Hash(img), nil
} }

View File

@@ -4,6 +4,7 @@ package sha1
import ( import (
"crypto/sha1" "crypto/sha1"
"encoding/hex" "encoding/hex"
"fmt"
"io" "io"
"os" "os"
) )
@@ -24,13 +25,13 @@ func Sha1Hex(data []byte) string {
func SumFile(file string) ([]byte, error) { func SumFile(file string) ([]byte, error) {
f, err := os.Open(file) f, err := os.Open(file)
if err != nil { if err != nil {
return nil, err return nil, fmt.Errorf("未能打开指定文件,%w", err)
} }
defer f.Close() defer f.Close()
hasher := sha1.New() hasher := sha1.New()
if _, err := io.Copy(hasher, f); err != nil { if _, err := io.Copy(hasher, f); err != nil {
return nil, err return nil, fmt.Errorf("未能读取指定文件的内容,%w", err)
} }
return hasher.Sum(nil), nil return hasher.Sum(nil), nil
} }

View File

@@ -4,6 +4,7 @@ package sha256
import ( import (
"crypto/sha256" "crypto/sha256"
"encoding/hex" "encoding/hex"
"fmt"
"hash" "hash"
"io" "io"
"os" "os"
@@ -45,8 +46,7 @@ func Sha256_224Hex(data []byte) string {
// 根据给定位数计算一个字节数组的Sha256校验和返回字节数组。 // 根据给定位数计算一个字节数组的Sha256校验和返回字节数组。
func Sum256(data []byte, bitSize ...int) []byte { func Sum256(data []byte, bitSize ...int) []byte {
length := append(bitSize, 256) hasher := hasherSelect(append(bitSize, 256)[0])
hasher := hasherSelect(length[0])
hasher.Write(data) hasher.Write(data)
return hasher.Sum(nil) return hasher.Sum(nil)
} }
@@ -60,13 +60,13 @@ func Sum256Hex(data []byte, bitSize ...int) string {
func SumFile256(file string, bitSize ...int) ([]byte, error) { func SumFile256(file string, bitSize ...int) ([]byte, error) {
f, err := os.Open(file) f, err := os.Open(file)
if err != nil { if err != nil {
return nil, err return nil, fmt.Errorf("未能打开指定文件,%w", err)
} }
defer f.Close() defer f.Close()
hasher := hasherSelect(bitSize[0]) hasher := hasherSelect(append(bitSize, 256)[0])
if _, err := io.Copy(hasher, f); err != nil { if _, err := io.Copy(hasher, f); err != nil {
return nil, err return nil, fmt.Errorf("未能读取指定文件的内容,%w", err)
} }
return hasher.Sum(nil), nil return hasher.Sum(nil), nil
} }

View File

@@ -4,6 +4,7 @@ package sha512
import ( import (
"crypto/sha512" "crypto/sha512"
"encoding/hex" "encoding/hex"
"fmt"
"hash" "hash"
"io" "io"
"os" "os"
@@ -76,14 +77,14 @@ func Sum512Hex(data []byte, bitSize ...int) string {
func SumFile512(path string, bitSize ...int) ([]byte, error) { func SumFile512(path string, bitSize ...int) ([]byte, error) {
f, err := os.Open(path) f, err := os.Open(path)
if err != nil { if err != nil {
return nil, err return nil, fmt.Errorf("未能打开指定文件,%w", err)
} }
defer f.Close() defer f.Close()
length := append(bitSize, 512) length := append(bitSize, 512)
var hasher = hasherSelect(length[0]) var hasher = hasherSelect(length[0])
if _, err := io.Copy(hasher, f); err != nil { if _, err := io.Copy(hasher, f); err != nil {
return nil, err return nil, fmt.Errorf("未能读取指定文件的内容,%w", err)
} }
return hasher.Sum(nil), nil return hasher.Sum(nil), nil
} }

View File

@@ -0,0 +1,7 @@
package hail
type HailAlgorithmNotInitializedError struct{}
func (e *HailAlgorithmNotInitializedError) Error() string {
return "冰雹ID生成算法尚未初始化"
}

73
serial_code/hail/hail.go Normal file
View File

@@ -0,0 +1,73 @@
// 提供基于雪花ID生成算法改进的短日期短主机板冰雹ID生成算法
package hail
import (
"fmt"
"sync"
"time"
"archgrid.xyz/ag/toolsbox/types"
)
// 用于记录当前冰雹ID组成内容的数据结构
type HailAlgorithm struct {
hostSerial int64
lastTimestamp int64
lastSequence int64
lock sync.Mutex
}
var hailAlgorithmInstance *HailAlgorithm
// 获取当前已经完成初始化的冰雹ID生成算法实例如果尚未完成初始化则会返回未初始化的错误。
func Get() (*HailAlgorithm, error) {
if hailAlgorithmInstance == nil {
return nil, &HailAlgorithmNotInitializedError{}
}
return hailAlgorithmInstance, nil
}
// 指定一个主机编号并完成冰雹ID生成算法的初始化。
func Initialize(hostSerial int64) {
hailAlgorithmInstance = &HailAlgorithm{
hostSerial: hostSerial,
lastTimestamp: types.Timestamp(),
lastSequence: 0,
lock: sync.Mutex{},
}
}
// 返回一个可用的时间戳,如果主机发生了时间回拨,那么将等待一秒钟。
func (h *HailAlgorithm) timestamp() int64 {
for {
timestamp := types.Timestamp()
if timestamp == h.lastTimestamp {
h.lastTimestamp = timestamp
return timestamp
} else if timestamp > h.lastTimestamp {
h.lastTimestamp = timestamp
h.lastSequence = 0
return timestamp
}
time.Sleep(1 * time.Second)
}
}
// 生成一个冰雹ID。
func (h *HailAlgorithm) Generate() int64 {
h.lock.Lock()
defer h.lock.Unlock()
timestamp := h.timestamp()
h.lastSequence++
return (timestamp << 20) | ((h.hostSerial & 0xffff) << 16) | (h.lastSequence & 0xffff_ffff)
}
// 生成一个冰雹ID并将其转换为字符串。
func (h *HailAlgorithm) GenerateString() string {
return fmt.Sprintf("%017d", h.Generate())
}
// 生成一个冰雹ID将其转换为字符串并附加指定的前缀
func (h *HailAlgorithm) GeneratePrefixedString(prefix string) string {
return fmt.Sprintf("%s%s", prefix, h.GenerateString())
}

View File

@@ -0,0 +1,13 @@
package uuidv7
type UUIDv7GeneratorNotInitializedError struct{}
func (e *UUIDv7GeneratorNotInitializedError) Error() string {
return "UUIDv7生成器尚未初始化"
}
type UUIDv7NodeIDExceededError struct{}
func (e *UUIDv7NodeIDExceededError) Error() string {
return "UUIDv7节点ID超出范围"
}

258
serial_code/uuidv7/uuid.go Normal file
View File

@@ -0,0 +1,258 @@
package uuidv7
import (
"crypto/rand"
"encoding/hex"
"fmt"
"strings"
"sync"
"time"
"archgrid.xyz/ag/toolsbox/serialize/base36"
"archgrid.xyz/ag/toolsbox/serialize/base64"
)
const (
epoch = 1645566142222 // 自定义纪元2022-02-22 22:22:22.222 UTC
nodeBits = 5 // 主机编号容量为032
sequenceBits = 18 // 每毫秒生成序列号最大为2^18-1即262144个
maxNodeID = (1 << nodeBits) - 1
maxSequence = (1 << sequenceBits) - 1
timestampShift = nodeBits + sequenceBits
nodeShift = sequenceBits
)
type UUIDv7Generator struct {
locker sync.Mutex
nodeID int64
lastTime int64
sequence int64
}
type UUIDv7Components struct {
Timestamp int64 // 毫秒时间戳(相对于自定义纪元)
NodeID int64 // 5位节点ID
Sequence int64 // 18位序列号
Version int // 版本号应为7
Variant int // 变体应为2表示10xx
RawBytes [16]byte // 原始字节
}
var generatorInstance *UUIDv7Generator
// 获取UUIDv7生成器实例。如果实例尚未初始化则返回错误。
func Generator() (*UUIDv7Generator, error) {
if generatorInstance == nil {
return nil, &UUIDv7GeneratorNotInitializedError{}
}
return generatorInstance, nil
}
// 指定一个主机编号并完成UUIDv7生成器的初始化。如果主机编号超出范围则返回错误。
func Initialize(hostSerial int64) error {
if hostSerial < 0 || hostSerial > maxNodeID {
return &UUIDv7NodeIDExceededError{}
}
generatorInstance = &UUIDv7Generator{
nodeID: hostSerial,
lastTime: epoch,
}
return nil
}
// 获取当前时间对应的新纪元毫秒时间戳。
func (g *UUIDv7Generator) Now() int64 {
return time.Now().UnixMilli() - epoch
}
// 按顺序生成一个UUIDv7序号组件。
func (g *UUIDv7Generator) Next() UUIDv7Components {
g.locker.Lock()
defer g.locker.Unlock()
now := g.Now()
if now < g.lastTime {
// 防止时间回拔的情况,发生回拔时,直接使用上一次的时间戳
now = g.lastTime
}
if now == g.lastTime {
g.sequence++
if g.sequence > maxSequence {
time.Sleep(time.Millisecond)
now = g.Now()
g.sequence = 0
}
} else {
g.sequence = 0
}
g.lastTime = now
return UUIDv7Components{
Timestamp: now,
NodeID: g.nodeID,
Sequence: g.sequence,
Version: 7,
Variant: 2,
}
}
// 读取随机字节
func (c *UUIDv7Components) readRandom(bytes []byte) error {
_, err := rand.Read(bytes)
return err
}
// 获取UUIDv7原始字节数组
func (c *UUIDv7Components) Bytes() [16]byte {
// 构造 UUID
var uuid [16]byte
// 时间戳48 位)
timestamp := uint64(c.Timestamp) << timestampShift
seqAndNode := (uint64(c.Sequence) << nodeShift) | uint64(c.NodeID)
// 写入高位时间戳
uuid[0] = byte(timestamp >> 56)
uuid[1] = byte(timestamp >> 48)
uuid[2] = byte(timestamp >> 40)
uuid[3] = byte(timestamp >> 32)
uuid[4] = byte(timestamp >> 24)
uuid[5] = byte(timestamp >> 16)
// 写入低位时间戳 + 版本号4 位)
uuid[6] = byte((timestamp >> 8) | 0x70) // version 7
uuid[7] = byte(timestamp)
// 写入 seq + node
uuid[8] = byte((seqAndNode >> 16) | 0x80) // variant 10xx
uuid[9] = byte(seqAndNode >> 8)
uuid[10] = byte(seqAndNode)
// 剩余位全为 0可扩展为更多节点 ID 或随机数)
randomBytes := make([]byte, 5)
if err := c.readRandom(randomBytes); err != nil {
// 如果随机数生成失败,使用时间相关值作为后备
t := time.Now().UnixNano()
randomBytes[0] = byte(t)
randomBytes[1] = byte(t >> 8)
randomBytes[2] = byte(t >> 16)
randomBytes[3] = byte(t >> 24)
randomBytes[4] = byte(c.Sequence)
}
copy(uuid[11:16], randomBytes)
return uuid
}
// 获取UUIDv7字符串
func (c *UUIDv7Components) String() string {
uuid := c.Bytes()
return fmt.Sprintf("%x-%x-%x-%x-%x",
uuid[0:4],
uuid[4:6],
uuid[6:8],
uuid[8:10],
uuid[10:16])
}
// 获取UUIDv7的Base64格式字符串
func (c *UUIDv7Components) ToBase64() string {
uuid := c.Bytes()
return base64.ToBase64(uuid[:])
}
// 获取UUIDv7的Base36格式字符串
func (c *UUIDv7Components) ToBase36() string {
uuid := c.Bytes()
return base36.Encode(uuid[:])
}
// 与另一个UUIDv7进行比较按照时间戳、序列号、节点ID进行排序
func (c *UUIDv7Components) Compare(b *UUIDv7Components) int {
if c.Timestamp > b.Timestamp {
return 1
}
if c.Timestamp < b.Timestamp {
return -1
}
if c.Sequence > b.Sequence {
return 1
}
if c.Sequence < b.Sequence {
return -1
}
if c.NodeID > b.NodeID {
return -1
}
if c.NodeID < b.NodeID {
return 1
}
return 0
}
// 对解析后的UUIDv7进行比较按照时间戳、序列号、节点ID进行排序
func CompareUUIDv7(a, b *UUIDv7Components) int {
return a.Compare(b)
}
// 从字节数组解析 UUIDv7
func ParseUUIDv7FromBytes(data [16]byte) (*UUIDv7Components, error) {
// 提取时间戳前48位
timestamp := (int64(data[0]) << 40) |
(int64(data[1]) << 32) |
(int64(data[2]) << 24) |
(int64(data[3]) << 16) |
(int64(data[4]) << 8) |
int64(data[5])
// 提取版本号第6字节的高4位
version := int(data[6] >> 4)
// 提取变体第8字节的高2位
variant := int(data[8] >> 6)
// 提取序列号和节点ID
// 第8字节的低2位 + 第9字节 + 第10字节的高3位组成23位
seqAndNode := (int64(data[8]&0x3F) << 16) | // 第8字节低6位
(int64(data[9]) << 8) | // 第9字节
int64(data[10]) // 第10字节
// 分离序列号高18位和节点ID低5位
sequence := seqAndNode >> 5
nodeID := seqAndNode & 0x1F
return &UUIDv7Components{
Timestamp: timestamp,
NodeID: nodeID,
Sequence: sequence,
Version: version,
Variant: variant,
RawBytes: data,
}, nil
}
// 从字符串解析 UUIDv7
func ParseUUIDv7FromString(uuidStr string) (*UUIDv7Components, error) {
// 移除连字符并验证长度
cleanStr := strings.ReplaceAll(uuidStr, "-", "")
if len(cleanStr) != 32 {
return nil, fmt.Errorf("无效的UUIDv7字符串长度")
}
// 解码十六进制字符串
bytes, err := hex.DecodeString(cleanStr)
if err != nil {
return nil, fmt.Errorf("无效的UUIDv7字符串格式: %v", err)
}
// 转换为数组
var uuidBytes [16]byte
copy(uuidBytes[:], bytes)
return ParseUUIDv7FromBytes(uuidBytes)
}
// 从Base64格式字符串解析 UUIDv7
func ParseUUIDv7FromBase64(base64Str string) (*UUIDv7Components, error) {
bytes, err := base64.FromBase64(base64Str)
if err != nil {
return nil, fmt.Errorf("无效的Base64格式字符串: %v", err)
}
return ParseUUIDv7FromBytes([16]byte(bytes))
}
// 从Base36格式字符串解析 UUIDv7
func ParseUUIDv7FromBase36(base36Str string) (*UUIDv7Components, error) {
bytes, err := base36.Decode(base36Str)
if err != nil {
return nil, fmt.Errorf("无效的Base36格式字符串: %v", err)
}
return ParseUUIDv7FromBytes([16]byte(bytes))
}

108
serialize/base36/base36.go Normal file
View File

@@ -0,0 +1,108 @@
package base36
import (
"fmt"
"math/big"
"strings"
)
// Encode 将字节数据编码为Base36字符串(大写),使用=作为padding字符
func Encode(src []byte) string {
if len(src) == 0 {
return ""
}
// 将字节转换为big.Int
num := new(big.Int).SetBytes(src)
// 如果输入为全零字节,则直接返回"0"
if num.Cmp(big.NewInt(0)) == 0 {
return "0"
}
// 进行Base36编码
var result strings.Builder
base := big.NewInt(36)
zero := big.NewInt(0)
remainder := new(big.Int)
// 重复除以36获取余数作为字符
for num.Cmp(zero) > 0 {
num.DivMod(num, base, remainder)
digit := remainder.Int64()
if digit < 10 {
result.WriteString(fmt.Sprintf("%d", digit))
} else {
result.WriteString(fmt.Sprintf("%c", 'A'+digit-10))
}
}
// 反转字符串,因为我们是从低位开始计算的
encoded := result.String()
runes := []rune(encoded)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
}
return string(runes)
}
// Decode 将Base36字符串(可为任意大小写)解码为字节数组
func Decode(src string) ([]byte, error) {
if src == "" {
return []byte{}, nil
}
// 移除padding字符
src = strings.ReplaceAll(src, "=", "")
src = strings.ToUpper(src)
// 使用big.Int进行解码
num := big.NewInt(0)
base := big.NewInt(36)
for _, char := range src {
var digit int64
switch {
case char >= '0' && char <= '9':
digit = int64(char - '0')
case char >= 'A' && char <= 'Z':
digit = int64(char - 'A' + 10)
default:
return nil, fmt.Errorf("invalid character %c in base36 string", char)
}
num.Mul(num, base)
num.Add(num, big.NewInt(digit))
}
// 转换为字节数组
return num.Bytes(), nil
}
// EncodeToString 是Encode的别名用于保持与标准库一致的命名
func EncodeToString(src []byte) string {
return Encode(src)
}
// DecodeString 是Decode的别名用于保持与标准库一致的命名
func DecodeString(src string) ([]byte, error) {
return Decode(src)
}
// EncodeInt64 将int64转换为Base36字符串
func EncodeInt64(num int64) string {
return EncodeToString(big.NewInt(num).Bytes())
}
// DecodeToInt64 将Base36字符串解码为int64
func DecodeToInt64(src string) (int64, error) {
bytes, err := DecodeString(src)
if err != nil {
return 0, err
}
return new(big.Int).SetBytes(bytes).Int64(), nil
}

View File

@@ -0,0 +1,42 @@
package base36
import (
"fmt"
"testing"
)
func FuzzEncode(f *testing.F) {
testCases := []string{"a", "abc", "uuid"}
for _, tc := range testCases {
f.Add(tc)
}
f.Fuzz(func(t *testing.T, a string) {
encoded := Encode([]byte(a))
redecoded, err := Decode(encoded)
fmt.Printf("Origin: %s, Encoded: %s\n", a, encoded)
if err != nil {
t.Errorf("Decode(%q) failed: %v", encoded, err)
}
if string(redecoded) != a {
t.Errorf("Decode(%q) = %q, want %q", encoded, redecoded, a)
}
})
}
func FuzzEncodeInt64(f *testing.F) {
testCases := []int64{1, 6, 34598347534, 234532543, 2342546456, 34587639284756293}
for _, tc := range testCases {
f.Add(tc)
}
f.Fuzz(func(t *testing.T, a int64) {
encoded := EncodeInt64(a)
redecoded, err := DecodeToInt64(encoded)
fmt.Printf("Origin: %d, Encoded: %s\n", a, encoded)
if err != nil {
t.Errorf("Decode(%q) failed: %v", encoded, err)
}
if redecoded != a {
t.Errorf("Decode(%q) = %q, want %q", encoded, redecoded, a)
}
})
}