This repository has been archived by the owner on Sep 30, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpacker.go
77 lines (71 loc) · 1.65 KB
/
packer.go
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
package macaronsign
import (
"encoding/base64"
"encoding/json"
"errors"
"strings"
"time"
"unicode/utf8"
)
const signerVersion int = 1
var urlsafe = base64.RawURLEncoding
func (s Signer) pack(data []byte) []byte {
salt := make([]byte, 8)
Head, _ := json.Marshal(header{
Version: signerVersion,
Exp: s.EXP + time.Now().UTC().Unix(),
Salt: urlsafe.EncodeToString(salt),
})
sHead := urlsafe.EncodeToString(Head)
Body, _ := json.Marshal(payload{
Body: urlsafe.EncodeToString(data),
BodyLen: len(data),
})
sBody := urlsafe.EncodeToString(Body)
return []byte(sHead + "$" + sBody)
}
//ErrExpired : Token has expired
var ErrExpired error = errors.New("expired token")
func (s Signer) unpack(data []byte) ([]byte, error) {
if !utf8.Valid(data) {
return nil, errors.New("encoding error")
}
sData := string(data)
parts := strings.Split(sData, "$")
if len(parts) != 2 {
return nil, errors.New("encoding error")
}
HeadPart, err := urlsafe.DecodeString(parts[0])
if err != nil {
return nil, err
}
Bodypart, err := urlsafe.DecodeString(parts[1])
if err != nil {
return nil, err
}
body := new(payload)
head := new(header)
err = json.Unmarshal(HeadPart, head)
if err != nil {
return nil, err
}
err = json.Unmarshal(Bodypart, body)
if err != nil {
return nil, err
}
if head.Exp < time.Now().UTC().Unix() {
bodyByte, err := urlsafe.DecodeString(body.Body)
if err != nil {
return nil, ErrExpired
}
return bodyByte, ErrExpired
}
bodyByte, err := urlsafe.DecodeString(body.Body)
if err != nil {
return nil, err
}
if len(bodyByte) != body.BodyLen {
return bodyByte, errors.New("Wrong Body length")
}
return bodyByte, nil
}