66 lines
1.3 KiB
Go
66 lines
1.3 KiB
Go
package base62json
|
|
|
|
import (
|
|
"fmt"
|
|
"unsafe"
|
|
|
|
"git.fsdpf.net/go/jsonpack"
|
|
|
|
"github.com/jxskiss/base62"
|
|
"github.com/samber/lo"
|
|
)
|
|
|
|
const cursor = 59
|
|
const encodeStd = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
|
|
|
|
var bs62 *base62.Encoding
|
|
|
|
func init() {
|
|
bs62 = base62.NewEncoding(encodeStd)
|
|
}
|
|
|
|
// 项目入口
|
|
func GenerateProjectSecret(key, secret string) ([]byte, error) {
|
|
appSecret := lo.FindUniques([]byte(secret))
|
|
|
|
if len(secret) != 62 {
|
|
return nil, fmt.Errorf("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 string) error {
|
|
if len(secret) != 62 {
|
|
return fmt.Errorf("encoding alphabet is not 62-bytes long")
|
|
}
|
|
bs62 = base62.NewEncoding(secret)
|
|
return nil
|
|
}
|
|
|
|
func Encode[T []any | map[string]any](data T) (string, error) {
|
|
str, err := jsonpack.Pack(data)
|
|
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
stringData := unsafe.StringData(str)
|
|
|
|
return bs62.EncodeToString(unsafe.Slice(stringData, len(str))), nil
|
|
}
|
|
|
|
func Decode(str string) (string, error) {
|
|
json, err := bs62.DecodeString(str)
|
|
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
return jsonpack.Unpack(*(*string)(unsafe.Pointer(&json)))
|
|
}
|