...
1
2
3
4
5
6
7 package byteutil
8
9
10
11
12
13 func GfnDouble(input []byte) []byte {
14 if len(input) != 16 {
15 panic("Doubling in GFn only implemented for n = 128")
16 }
17
18
19 shifted := ShiftBytesLeft(input)
20 shifted[15] ^= ((input[0] >> 7) * 0x87)
21 return shifted
22 }
23
24
25 func ShiftBytesLeft(x []byte) []byte {
26 l := len(x)
27 dst := make([]byte, l)
28 for i := 0; i < l-1; i++ {
29 dst[i] = (x[i] << 1) | (x[i+1] >> 7)
30 }
31 dst[l-1] = x[l-1] << 1
32 return dst
33 }
34
35
36 func ShiftNBytesLeft(dst, x []byte, n int) {
37
38 copy(dst, x[n/8:])
39
40
41 bits := uint(n % 8)
42 l := len(dst)
43 for i := 0; i < l-1; i++ {
44 dst[i] = (dst[i] << bits) | (dst[i+1] >> uint(8-bits))
45 }
46 dst[l-1] = dst[l-1] << bits
47
48
49 dst = append(dst, make([]byte, n/8)...)
50 }
51
52
53 func XorBytesMut(X, Y []byte) {
54 for i := 0; i < len(X); i++ {
55 X[i] ^= Y[i]
56 }
57 }
58
59
60 func XorBytes(Z, X, Y []byte) {
61 for i := 0; i < len(X); i++ {
62 Z[i] = X[i] ^ Y[i]
63 }
64 }
65
66
67 func RightXor(X, Y []byte) []byte {
68 offset := len(X) - len(Y)
69 xored := make([]byte, len(X))
70 copy(xored, X)
71 for i := 0; i < len(Y); i++ {
72 xored[offset+i] ^= Y[i]
73 }
74 return xored
75 }
76
77
78
79
80
81 func SliceForAppend(in []byte, n int) (head, tail []byte) {
82 if total := len(in) + n; cap(in) >= total {
83 head = in[:total]
84 } else {
85 head = make([]byte, total)
86 copy(head, in)
87 }
88 tail = head[len(in):]
89 return
90 }
91
View as plain text