|
5 | 5 | package asn1
|
6 | 6 |
|
7 | 7 | import (
|
| 8 | + "bytes" |
8 | 9 | "errors"
|
9 | 10 | "fmt"
|
10 | 11 | "math/big"
|
11 | 12 | "reflect"
|
| 13 | + "sort" |
12 | 14 | "time"
|
13 | 15 | "unicode/utf8"
|
14 | 16 | )
|
@@ -78,6 +80,60 @@ func (m multiEncoder) Encode(dst []byte) {
|
78 | 80 | }
|
79 | 81 | }
|
80 | 82 |
|
| 83 | +type octetSorter [][]byte |
| 84 | + |
| 85 | +func (s octetSorter) Len() int { |
| 86 | + return len(s) |
| 87 | +} |
| 88 | + |
| 89 | +func (s octetSorter) Swap(i, j int) { |
| 90 | + s[i], s[j] = s[j], s[i] |
| 91 | +} |
| 92 | + |
| 93 | +func (s octetSorter) Less(i, j int) bool { |
| 94 | + // Since we are using bytes.Compare to compare TLV encodings we |
| 95 | + // don't need to right pad s[i] and s[j] to the same length as |
| 96 | + // suggested in X690. If len(s[i]) < len(s[j]) the length octet of |
| 97 | + // s[i], which is the first determining byte, will inherently be |
| 98 | + // smaller than the length octet of s[j]. This lets us skip the |
| 99 | + // padding step. |
| 100 | + return bytes.Compare(s[i], s[j]) < 0 |
| 101 | +} |
| 102 | + |
| 103 | +type setEncoder []encoder |
| 104 | + |
| 105 | +func (s setEncoder) Len() int { |
| 106 | + var size int |
| 107 | + for _, e := range s { |
| 108 | + size += e.Len() |
| 109 | + } |
| 110 | + return size |
| 111 | +} |
| 112 | + |
| 113 | +func (s setEncoder) Encode(dst []byte) { |
| 114 | + // Per X690 Section 11.6: The encodings of the component values of a |
| 115 | + // set-of value shall appear in ascending order, the encodings being |
| 116 | + // compared as octet strings with the shorter components being padded |
| 117 | + // at their trailing end with 0-octets. |
| 118 | + // |
| 119 | + // First we encode each element to its TLV encoding and then use |
| 120 | + // octetSort to get the ordering expected by X690 DER rules before |
| 121 | + // writing the sorted encodings out to dst. |
| 122 | + l := make([][]byte, len(s)) |
| 123 | + for i, e := range s { |
| 124 | + l[i] = make([]byte, e.Len()) |
| 125 | + e.Encode(l[i]) |
| 126 | + } |
| 127 | + |
| 128 | + sort.Sort(octetSorter(l)) |
| 129 | + |
| 130 | + var off int |
| 131 | + for _, b := range l { |
| 132 | + copy(dst[off:], b) |
| 133 | + off += len(b) |
| 134 | + } |
| 135 | +} |
| 136 | + |
81 | 137 | type taggedEncoder struct {
|
82 | 138 | // scratch contains temporary space for encoding the tag and length of
|
83 | 139 | // an element in order to avoid extra allocations.
|
@@ -511,6 +567,9 @@ func makeBody(value reflect.Value, params fieldParameters) (e encoder, err error
|
511 | 567 | }
|
512 | 568 | }
|
513 | 569 |
|
| 570 | + if params.set { |
| 571 | + return setEncoder(m), nil |
| 572 | + } |
514 | 573 | return multiEncoder(m), nil
|
515 | 574 | }
|
516 | 575 | case reflect.String:
|
|
0 commit comments