-
Notifications
You must be signed in to change notification settings - Fork 5
/
pcpcrypto_utils.go
53 lines (47 loc) · 1.51 KB
/
pcpcrypto_utils.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
package pcpcrypto
import (
"bytes"
"encoding/binary"
"fmt"
"golang.org/x/sys/windows"
)
// utf16BytesToString transforms a []byte which contains a wide char string in LE
// into its []uint16 corresponding representation,
// then returns the UTF-8 encoding of the UTF-16 sequence,
// with a terminating NUL removed. If after converting the []byte into
// a []uint16, there is a NUL uint16, the conversion to string stops
// at that NUL uint16.
func utf16BytesToString(buf []byte) (string, error) {
if len(buf)%2 != 0 {
return "", fmt.Errorf("input is not a valid byte representation of a wide char string in LE")
}
b := make([]uint16, len(buf)/2)
// LPCSTR (Windows' representation of utf16) is always little endian.
if err := binary.Read(bytes.NewReader(buf), binary.LittleEndian, b); err != nil {
return "", err
}
return windows.UTF16ToString(b), nil
}
// stringToUtf16Bytes returns the UTF-16 encoding of the UTF-8 string
// str, as a byte array with a terminating NUL added. If str contains a NUL byte at any
// location, it returns (nil, EINVAL).
func stringToUtf16Bytes(str string) ([]byte, error) {
if str == "" {
return nil, nil
}
utf16Str, err := windows.UTF16FromString(str)
if err != nil {
return nil, err
}
bytesStr := make([]byte, len(utf16Str)*2)
j := 0
for _, utf16 := range utf16Str {
b := make([]byte, 2)
// LPCSTR (Windows' representation of utf16) is always little endian.
binary.LittleEndian.PutUint16(b, utf16)
bytesStr[j] = b[0]
bytesStr[j+1] = b[1]
j += 2
}
return bytesStr, nil
}