This repository was archived by the owner on Jan 22, 2024. It is now read-only.
forked from iromli/go-itsdangerous
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathitsdangerous.go
More file actions
86 lines (73 loc) · 1.59 KB
/
itsdangerous.go
File metadata and controls
86 lines (73 loc) · 1.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/*
Package itsdangerous implements various functions to deal with untrusted sources.
Mainly useful for web applications.
This package exists purely as a port of https://github.com/mitsuhiko/itsdangerous,
where the original version is written in Python.
*/
package itsdangerous
import (
"bytes"
"compress/zlib"
"encoding/base64"
"io/ioutil"
"time"
)
func base64Encode(b []byte) []byte {
dst := make([]byte, base64.URLEncoding.EncodedLen(len(b)))
base64.URLEncoding.Encode(dst, b)
for i := len(dst) - 1; i > 0; i-- {
if dst[i] == '=' {
dst = dst[:i]
}
}
return dst
}
func ZBase64Encode(b []byte) []byte {
isCompressed := false
var zbuf bytes.Buffer
zw := zlib.NewWriter(&zbuf)
zw.Write(b)
if err := zw.Close(); err == nil {
cb := zbuf.Bytes()
if len(cb) < len(b)+1 {
isCompressed = true
b = cb
}
}
dst := base64Encode(b)
if isCompressed {
dst = append([]byte{'.'}, dst...)
}
return dst
}
func base64Decode(b []byte) ([]byte, error) {
// if leading '.' itsdangerous has compressed this with zlib
decompress := false
if b[0] == '.' {
decompress = true
b = b[1:]
}
for i := 0; i < len(b)%4; i++ {
b = append(b, '=')
}
dst := make([]byte, base64.URLEncoding.DecodedLen(len(b)))
n, err := base64.URLEncoding.Decode(dst, b)
if err != nil {
return nil, err
}
dst = dst[:n]
// if leading '.' decompress now
if decompress {
br := bytes.NewReader(dst)
r, err := zlib.NewReader(br)
if err != nil {
return nil, err
}
done, err := ioutil.ReadAll(r)
return done, err
}
return dst, nil
}
func getTimestamp() uint32 {
return uint32(time.Now().Unix())
}