...
1
2
3
4
5 package pkcs12
6
7 import (
8 "errors"
9 "unicode/utf16"
10 )
11
12
13 func bmpString(s string) ([]byte, error) {
14
15
16
17
18
19
20
21 ret := make([]byte, 0, 2*len(s)+2)
22
23 for _, r := range s {
24 if t, _ := utf16.EncodeRune(r); t != 0xfffd {
25 return nil, errors.New("pkcs12: string contains characters that cannot be encoded in UCS-2")
26 }
27 ret = append(ret, byte(r/256), byte(r%256))
28 }
29
30 return append(ret, 0, 0), nil
31 }
32
33 func decodeBMPString(bmpString []byte) (string, error) {
34 if len(bmpString)%2 != 0 {
35 return "", errors.New("pkcs12: odd-length BMP string")
36 }
37
38
39 if l := len(bmpString); l >= 2 && bmpString[l-1] == 0 && bmpString[l-2] == 0 {
40 bmpString = bmpString[:l-2]
41 }
42
43 s := make([]uint16, 0, len(bmpString)/2)
44 for len(bmpString) > 0 {
45 s = append(s, uint16(bmpString[0])<<8+uint16(bmpString[1]))
46 bmpString = bmpString[2:]
47 }
48
49 return string(utf16.Decode(s)), nil
50 }
51
View as plain text