gitee.com/quant1x/gox@v1.21.2/encoding/base64/base64.go (about) 1 package base64 2 3 import ( 4 "encoding/base64" 5 "gitee.com/quant1x/gox/api" 6 "math/rand" 7 "slices" 8 "time" 9 ) 10 11 const ( 12 BASE64CHAR = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" 13 ) 14 15 // Base64GetEncoder 生成一个新的base64的码表 16 func Base64GetEncoder() string { 17 encoder := slices.Clone(api.String2Bytes(BASE64CHAR)) 18 rand.Seed(time.Now().UnixNano()) 19 rand.Shuffle(len(encoder), func(i, j int) { 20 encoder[i], encoder[j] = encoder[j], encoder[i] 21 }) 22 return api.Bytes2String(encoder) 23 } 24 25 func getBase64Encoder(seed int64) string { 26 encoder := slices.Clone(api.String2Bytes(BASE64CHAR)) 27 rand.Seed(seed) 28 rand.Shuffle(len(encoder), func(i, j int) { 29 encoder[i], encoder[j] = encoder[j], encoder[i] 30 }) 31 return api.Bytes2String(encoder) 32 } 33 34 type PseudoBase64 struct { 35 base64Chars string 36 encoding *base64.Encoding 37 } 38 39 func NewBase64(encoder string) PseudoBase64 { 40 return PseudoBase64{ 41 base64Chars: encoder, 42 encoding: base64.NewEncoding(encoder), 43 } 44 } 45 46 func NewPseudoBase64(seed int64) PseudoBase64 { 47 encoder := getBase64Encoder(seed) 48 return PseudoBase64{ 49 base64Chars: encoder, 50 encoding: base64.NewEncoding(encoder), 51 } 52 } 53 54 func (codec PseudoBase64) Encode(s string) string { 55 return codec.encoding.EncodeToString(api.String2Bytes(s)) 56 } 57 58 func (codec PseudoBase64) Decode(s string) (string, error) { 59 data, err := codec.encoding.DecodeString(s) 60 if err != nil { 61 return "", err 62 } 63 return api.Bytes2String(data), nil 64 }