67 lines
1.1 KiB
Go
67 lines
1.1 KiB
Go
package base62json
|
|
|
|
import (
|
|
"errors"
|
|
|
|
"git.fsdpf.net/go/base62"
|
|
"git.fsdpf.net/go/jsonpack"
|
|
|
|
"github.com/samber/lo"
|
|
)
|
|
|
|
const cursor = 59
|
|
|
|
var bs62 *base62.Base62
|
|
|
|
func init() {
|
|
bs62 = base62.GetInstance()
|
|
}
|
|
|
|
// 项目入口
|
|
func GenerateProjectSecret(key, secret string) ([]byte, error) {
|
|
appSecret := lo.FindUniques([]byte(secret))
|
|
|
|
if len(appSecret) != 62 {
|
|
return nil, errors.New("Invalid secret")
|
|
}
|
|
|
|
for i := 0; i < len(key); i++ {
|
|
appSecret[key[i]%cursor], appSecret[cursor-(key[i]%cursor)] = appSecret[cursor-(key[i]%cursor)], appSecret[key[i]%cursor]
|
|
}
|
|
|
|
return appSecret, nil
|
|
}
|
|
|
|
func SetCharacters(secret []byte) error {
|
|
if res, err := bs62.SetCharacters(secret); err == nil {
|
|
bs62 = res
|
|
} else {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func Encode[T []any | map[string]any](data T) (string, error) {
|
|
str, err := jsonpack.Pack(data)
|
|
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
res := bs62.Encode([]byte(str))
|
|
|
|
return res, nil
|
|
}
|
|
|
|
func Decode(str string) (string, error) {
|
|
json, err := bs62.Decode(str)
|
|
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
data := string(json)
|
|
|
|
return jsonpack.Unpack(data)
|
|
}
|