This repository has been archived by the owner on May 16, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
/
util.go
112 lines (85 loc) · 2.17 KB
/
util.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package dkeyczar
import (
"bytes"
"encoding/base64"
"encoding/binary"
"math/big"
)
func bigIntBytes(value *big.Int) []byte {
absbytes := value.Bytes()
if absbytes[0]&0x80 != 0x00 {
zero := []byte{0x00}
return append(zero, absbytes...)
}
return absbytes
}
// A Web64 string is a base64 encoded string with a web-safe character set and no trailing equal signs.
func decodeWeb64String(key string) ([]byte, error) {
var equals string
switch len(key) % 4 {
case 0:
equals = ""
case 1:
equals = "==="
case 2:
equals = "=="
case 3:
equals = "="
}
return base64.URLEncoding.DecodeString(key + equals)
}
func encodeWeb64String(b []byte) string {
s := base64.URLEncoding.EncodeToString(b)
var i = len(s) - 1
for s[i] == '=' {
i--
}
return s[0 : i+1]
}
// Encode a list of arrays as a single byte-stream:
// <number_of_arrays> <len1> <array1> <len2> <array2> ...
// The number of arrays and lengths are big-endian uint32.
// The byte arrays themselves are sent as-is.
func lenPrefixPack(arrays ...[]byte) []byte {
data := 0
for _, a := range arrays {
data += len(a)
}
headers := 1 + (4 * len(arrays))
output := make([]byte, 0, headers+data)
buf := bytes.NewBuffer(output)
binary.Write(buf, binary.BigEndian, uint32(len(arrays)))
for _, a := range arrays {
binary.Write(buf, binary.BigEndian, uint32(len(a)))
buf.Write(a)
}
return buf.Bytes()
}
// Unpack a list of arrays packed with lenPrefixPack
func lenPrefixUnpack(packed []byte) [][]byte {
var numArrays uint32
buf := bytes.NewBuffer(packed)
binary.Read(buf, binary.BigEndian, &numArrays)
arrays := make([][]byte, numArrays)
for i := uint32(0); i < numArrays; i++ {
var size uint32
binary.Read(buf, binary.BigEndian, &size)
arrays[i] = make([]byte, size)
buf.Read(arrays[i])
}
return arrays
}
// only needed by AES?
func pkcs5pad(data []byte, blocksize int) []byte {
pad := blocksize - len(data)%blocksize
b := make([]byte, pad, pad)
for i := 0; i < pad; i++ {
b[i] = uint8(pad)
}
return append(data, b...)
}
func pkcs5unpad(data []byte) []byte {
pad := int(data[len(data)-1])
// FIXME: check that the padding bytes are all what we expect
return data[0 : len(data)-pad]
}