-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdecode.go
54 lines (44 loc) · 1.24 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
package base64encoding
import (
"errors"
"github.com/4kills/base64encoding/datatypes"
)
func (enc Encoder64) decode(s string) ([]byte, error) {
if len(s) < 1 {
return nil, errors.New("base64decoding error: string is empty")
}
bits, err := base64ToBits([]byte(s), enc.posMap)
if err != nil {
return nil, err
}
// cut away the first shifted byte
return bits.Expose()[1:], nil
}
func base64ToBits(s, posMap []byte) (datatypes.BitArray, error) {
bitLen := 6 // only need 6 bit for the numbers 0-63
shift := 8 - (len(s) * bitLen) % 8 // shifting the bit so i can cut them away more easily later
bits := datatypes.NewBitArray(shift + len(s) * bitLen)
for i := 0; i < len(s); i++ {
num, err := findValue(s[i], posMap)
if err != nil {
return datatypes.BitArray{}, err
}
curPart := i * bitLen
for j := 0; j < bitLen; j++ {
newBit := false
if (0x20 >> j) & num > 0 {
newBit = true
}
bits.Set(shift+ curPart + j, newBit)
}
}
return bits, nil
}
func findValue(s byte, posMap []byte) (int, error) {
position := posMap[s]
idx := int(position - 1)
if position == 0 {
return idx, errors.New("base64decoding: semantic: string was invalid, character not found in codeset")
}
return idx, nil
}