-
Notifications
You must be signed in to change notification settings - Fork 4
/
jwe_parse.go
61 lines (49 loc) · 1.27 KB
/
jwe_parse.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
package jwe
import (
"encoding/base64"
"encoding/json"
"errors"
"strings"
)
func ParseEncrypted(input string) (*jwe, error) {
if strings.HasPrefix(input, "{") {
// TODO (ortyomka): Add full version support
return nil, errors.New("don't support full JWE")
}
return parseEncryptedCompact(input)
}
func parseEncryptedCompact(input string) (*jwe, error) {
parts := strings.Split(input, ".")
if len(parts) != 5 {
return nil, errors.New("encrypted token contains an invalid number of segments")
}
jwe := &jwe{}
rawProtected, err := base64.RawURLEncoding.DecodeString(parts[0])
if err != nil {
return nil, err
}
if len(rawProtected) == 0 {
return nil, errors.New("protected headers are empty")
}
err = json.Unmarshal(rawProtected, &jwe.protected)
if err != nil {
return nil, errors.New("protected headers are not in JSON format")
}
jwe.recipientKey, err = base64.RawURLEncoding.DecodeString(parts[1])
if err != nil {
return nil, err
}
jwe.iv, err = base64.RawURLEncoding.DecodeString(parts[2])
if err != nil {
return nil, err
}
jwe.ciphertext, err = base64.RawURLEncoding.DecodeString(parts[3])
if err != nil {
return nil, err
}
jwe.tag, err = base64.RawURLEncoding.DecodeString(parts[4])
if err != nil {
return nil, err
}
return jwe, nil
}