-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdecode.go
77 lines (65 loc) · 2.11 KB
/
decode.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
// @author: Brian Wojtczak
// @copyright: 2024 by Brian Wojtczak
// @license: BSD-style license found in the LICENSE file
package altcha
import (
"encoding/base64"
"encoding/json"
"github.com/pkg/errors"
"strconv"
"strings"
"unicode"
)
// DecodeChallenge decodes output from NewChallengeEncoded.
func DecodeChallenge(encoded string) (msg Message, err error) {
if strings.HasPrefix(encoded, TextPrefix) {
return DecodeText(encoded)
}
return DecodeJSON([]byte(encoded))
}
// DecodeResponse decodes the response Message from the client.
func DecodeResponse(encoded string) (msg Message, err error) {
if strings.HasPrefix(encoded, TextPrefix) {
return DecodeText(encoded)
}
var jsonBytes []byte
jsonBytes, err = base64.StdEncoding.DecodeString(encoded)
if err != nil {
return msg, errors.Wrap(err, "invalid base64 encoding")
}
return DecodeJSON(jsonBytes)
}
// DecodeJSON decodes a Message stored in JSON format.
func DecodeJSON(encoded []byte) (msg Message, err error) {
err = json.Unmarshal(encoded, &msg)
return msg, errors.Wrap(err, "invalid message")
}
// DecodeText decodes the output from message.String().
func DecodeText(encoded string) (msg Message, err error) {
if !strings.HasPrefix(encoded, TextPrefix) {
return msg, errors.New("invalid text encoding of message")
}
// Split the input into fields based on commas and whitespace.
fields := strings.FieldsFunc(encoded[len(TextPrefix):], func(r rune) bool {
return r == ',' || r == ' ' || unicode.IsSpace(r)
})
// Extract the values from the fields.
for _, field := range fields {
switch {
case strings.HasPrefix(field, "algorithm="):
msg.Algorithm = field[len("algorithm="):]
case strings.HasPrefix(field, "salt="):
msg.Salt = field[len("salt="):]
case strings.HasPrefix(field, "number="):
msg.Number, err = strconv.Atoi(field[len("number="):])
case strings.HasPrefix(field, "challenge="):
msg.Challenge = field[len("challenge="):]
case strings.HasPrefix(field, "signature="):
msg.Signature = field[len("signature="):]
default:
return Message{}, errors.New("invalid message")
}
}
// Return the Message.
return msg, nil
}