...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package pkcs7
18
19 import (
20 "encoding/asn1"
21 "fmt"
22 )
23
24 type ErrNoAttribute struct {
25 ID asn1.ObjectIdentifier
26 }
27
28 func (e ErrNoAttribute) Error() string {
29 return fmt.Sprintf("attribute not found: %s", e.ID)
30 }
31
32
33 func (l *AttributeList) Bytes() ([]byte, error) {
34
35
36 encoded, err := asn1.Marshal(struct {
37 A []Attribute `asn1:"set"`
38 }{A: *l})
39 if err != nil {
40 return nil, err
41 }
42 var raw asn1.RawValue
43 if _, err := asn1.Unmarshal(encoded, &raw); err != nil {
44 return nil, err
45 }
46 return raw.Bytes, nil
47 }
48
49
50 func (l *AttributeList) GetOne(oid asn1.ObjectIdentifier, dest interface{}) error {
51 for _, raw := range *l {
52 if !raw.Type.Equal(oid) {
53 continue
54 }
55 rest, err := asn1.Unmarshal(raw.Values.Bytes, dest)
56 if err != nil {
57 return err
58 } else if len(rest) != 0 {
59 return fmt.Errorf("attribute %s: expected one, found multiple", oid)
60 } else {
61 return nil
62 }
63 }
64 return ErrNoAttribute{oid}
65 }
66
67
68 func (l *AttributeList) Add(oid asn1.ObjectIdentifier, obj interface{}) error {
69 value, err := asn1.Marshal(obj)
70 if err != nil {
71 return err
72 }
73 for _, attr := range *l {
74 if attr.Type.Equal(oid) {
75 attr.Values.Bytes = append(attr.Values.Bytes, value...)
76 return nil
77 }
78 }
79 *l = append(*l, Attribute{
80 Type: oid,
81 Values: asn1.RawValue{
82 Class: asn1.ClassUniversal,
83 Tag: asn1.TagSet,
84 IsCompound: true,
85 Bytes: value,
86 }})
87 return nil
88 }
89
View as plain text