Skip to content

Commit 85520c0

Browse files
author
Sol Cates
authored
Merge pull request #65 from jls5177/fix-ulong-cast
fix: issue casting byte slice to unsigned long type
2 parents 822acf7 + 4282254 commit 85520c0

File tree

2 files changed

+53
-1
lines changed

2 files changed

+53
-1
lines changed

common.go

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,23 @@ func ulongToBytes(n uint) []byte {
3636
}
3737

3838
func bytesToUlong(bs []byte) (n uint) {
39-
return *(*uint)(unsafe.Pointer(&bs[0])) // ugh
39+
sliceSize := len(bs)
40+
if sliceSize == 0 {
41+
return 0
42+
}
43+
44+
value := *(*uint)(unsafe.Pointer(&bs[0]))
45+
if sliceSize > C.sizeof_ulong {
46+
return value
47+
}
48+
49+
// truncate the value to the # of bits present in the byte slice since
50+
// the unsafe pointer will always grab/convert ULONG # of bytes
51+
var mask uint
52+
for i := 0; i < sliceSize; i++ {
53+
mask |= 0xff << uint(i * 8)
54+
}
55+
return value & mask
4056
}
4157

4258
func concat(slices ...[]byte) []byte {

common_test.go

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package crypto11
2+
3+
import (
4+
"testing"
5+
)
6+
7+
func TestULongMasking(t *testing.T) {
8+
ulongData := uint(0x33221100ddccbbaa)
9+
ulongSlice := ulongToBytes(ulongData)
10+
11+
// Build an slice that is longer than the size of a ulong
12+
extraLongSlice := append(ulongSlice, ulongSlice...)
13+
14+
tests := []struct {
15+
slice []uint8
16+
expected uint
17+
}{
18+
{ulongSlice[0:0], 0},
19+
{ulongSlice[0:1], 0xaa},
20+
{ulongSlice[0:2], 0xbbaa},
21+
{ulongSlice[0:3], 0xccbbaa},
22+
{ulongSlice[0:4], 0xddccbbaa},
23+
{ulongSlice[0:5], 0x00ddccbbaa},
24+
{ulongSlice[0:6], 0x1100ddccbbaa},
25+
{ulongSlice[0:7], 0x221100ddccbbaa},
26+
{ulongSlice[0:8], 0x33221100ddccbbaa},
27+
{extraLongSlice, 0x33221100ddccbbaa},
28+
}
29+
30+
for _, test := range tests {
31+
got := bytesToUlong(test.slice)
32+
if test.expected != got {
33+
t.Errorf("conversion failed: 0x%X != 0x%X", test.expected, got)
34+
}
35+
}
36+
}

0 commit comments

Comments
 (0)