libgo: Merge from revision 18783:00cce3a34d7e of master library.
[official-gcc.git] / libgo / go / encoding / asn1 / asn1.go
blobdfcbf920d0afcd34783582fb4be4b9326552e81d
1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // Package asn1 implements parsing of DER-encoded ASN.1 data structures,
6 // as defined in ITU-T Rec X.690.
7 //
8 // See also ``A Layman's Guide to a Subset of ASN.1, BER, and DER,''
9 // http://luca.ntop.org/Teaching/Appunti/asn1.html.
10 package asn1
12 // ASN.1 is a syntax for specifying abstract objects and BER, DER, PER, XER etc
13 // are different encoding formats for those objects. Here, we'll be dealing
14 // with DER, the Distinguished Encoding Rules. DER is used in X.509 because
15 // it's fast to parse and, unlike BER, has a unique encoding for every object.
16 // When calculating hashes over objects, it's important that the resulting
17 // bytes be the same at both ends and DER removes this margin of error.
19 // ASN.1 is very complex and this package doesn't attempt to implement
20 // everything by any means.
22 import (
23 "fmt"
24 "math/big"
25 "reflect"
26 "time"
29 // A StructuralError suggests that the ASN.1 data is valid, but the Go type
30 // which is receiving it doesn't match.
31 type StructuralError struct {
32 Msg string
35 func (e StructuralError) Error() string { return "asn1: structure error: " + e.Msg }
37 // A SyntaxError suggests that the ASN.1 data is invalid.
38 type SyntaxError struct {
39 Msg string
42 func (e SyntaxError) Error() string { return "asn1: syntax error: " + e.Msg }
44 // We start by dealing with each of the primitive types in turn.
46 // BOOLEAN
48 func parseBool(bytes []byte) (ret bool, err error) {
49 if len(bytes) != 1 {
50 err = SyntaxError{"invalid boolean"}
51 return
54 // DER demands that "If the encoding represents the boolean value TRUE,
55 // its single contents octet shall have all eight bits set to one."
56 // Thus only 0 and 255 are valid encoded values.
57 switch bytes[0] {
58 case 0:
59 ret = false
60 case 0xff:
61 ret = true
62 default:
63 err = SyntaxError{"invalid boolean"}
66 return
69 // INTEGER
71 // parseInt64 treats the given bytes as a big-endian, signed integer and
72 // returns the result.
73 func parseInt64(bytes []byte) (ret int64, err error) {
74 if len(bytes) > 8 {
75 // We'll overflow an int64 in this case.
76 err = StructuralError{"integer too large"}
77 return
79 for bytesRead := 0; bytesRead < len(bytes); bytesRead++ {
80 ret <<= 8
81 ret |= int64(bytes[bytesRead])
84 // Shift up and down in order to sign extend the result.
85 ret <<= 64 - uint8(len(bytes))*8
86 ret >>= 64 - uint8(len(bytes))*8
87 return
90 // parseInt treats the given bytes as a big-endian, signed integer and returns
91 // the result.
92 func parseInt32(bytes []byte) (int32, error) {
93 ret64, err := parseInt64(bytes)
94 if err != nil {
95 return 0, err
97 if ret64 != int64(int32(ret64)) {
98 return 0, StructuralError{"integer too large"}
100 return int32(ret64), nil
103 var bigOne = big.NewInt(1)
105 // parseBigInt treats the given bytes as a big-endian, signed integer and returns
106 // the result.
107 func parseBigInt(bytes []byte) *big.Int {
108 ret := new(big.Int)
109 if len(bytes) > 0 && bytes[0]&0x80 == 0x80 {
110 // This is a negative number.
111 notBytes := make([]byte, len(bytes))
112 for i := range notBytes {
113 notBytes[i] = ^bytes[i]
115 ret.SetBytes(notBytes)
116 ret.Add(ret, bigOne)
117 ret.Neg(ret)
118 return ret
120 ret.SetBytes(bytes)
121 return ret
124 // BIT STRING
126 // BitString is the structure to use when you want an ASN.1 BIT STRING type. A
127 // bit string is padded up to the nearest byte in memory and the number of
128 // valid bits is recorded. Padding bits will be zero.
129 type BitString struct {
130 Bytes []byte // bits packed into bytes.
131 BitLength int // length in bits.
134 // At returns the bit at the given index. If the index is out of range it
135 // returns false.
136 func (b BitString) At(i int) int {
137 if i < 0 || i >= b.BitLength {
138 return 0
140 x := i / 8
141 y := 7 - uint(i%8)
142 return int(b.Bytes[x]>>y) & 1
145 // RightAlign returns a slice where the padding bits are at the beginning. The
146 // slice may share memory with the BitString.
147 func (b BitString) RightAlign() []byte {
148 shift := uint(8 - (b.BitLength % 8))
149 if shift == 8 || len(b.Bytes) == 0 {
150 return b.Bytes
153 a := make([]byte, len(b.Bytes))
154 a[0] = b.Bytes[0] >> shift
155 for i := 1; i < len(b.Bytes); i++ {
156 a[i] = b.Bytes[i-1] << (8 - shift)
157 a[i] |= b.Bytes[i] >> shift
160 return a
163 // parseBitString parses an ASN.1 bit string from the given byte slice and returns it.
164 func parseBitString(bytes []byte) (ret BitString, err error) {
165 if len(bytes) == 0 {
166 err = SyntaxError{"zero length BIT STRING"}
167 return
169 paddingBits := int(bytes[0])
170 if paddingBits > 7 ||
171 len(bytes) == 1 && paddingBits > 0 ||
172 bytes[len(bytes)-1]&((1<<bytes[0])-1) != 0 {
173 err = SyntaxError{"invalid padding bits in BIT STRING"}
174 return
176 ret.BitLength = (len(bytes)-1)*8 - paddingBits
177 ret.Bytes = bytes[1:]
178 return
181 // OBJECT IDENTIFIER
183 // An ObjectIdentifier represents an ASN.1 OBJECT IDENTIFIER.
184 type ObjectIdentifier []int
186 // Equal reports whether oi and other represent the same identifier.
187 func (oi ObjectIdentifier) Equal(other ObjectIdentifier) bool {
188 if len(oi) != len(other) {
189 return false
191 for i := 0; i < len(oi); i++ {
192 if oi[i] != other[i] {
193 return false
197 return true
200 // parseObjectIdentifier parses an OBJECT IDENTIFIER from the given bytes and
201 // returns it. An object identifier is a sequence of variable length integers
202 // that are assigned in a hierarchy.
203 func parseObjectIdentifier(bytes []byte) (s []int, err error) {
204 if len(bytes) == 0 {
205 err = SyntaxError{"zero length OBJECT IDENTIFIER"}
206 return
209 // In the worst case, we get two elements from the first byte (which is
210 // encoded differently) and then every varint is a single byte long.
211 s = make([]int, len(bytes)+1)
213 // The first varint is 40*value1 + value2:
214 // According to this packing, value1 can take the values 0, 1 and 2 only.
215 // When value1 = 0 or value1 = 1, then value2 is <= 39. When value1 = 2,
216 // then there are no restrictions on value2.
217 v, offset, err := parseBase128Int(bytes, 0)
218 if err != nil {
219 return
221 if v < 80 {
222 s[0] = v / 40
223 s[1] = v % 40
224 } else {
225 s[0] = 2
226 s[1] = v - 80
229 i := 2
230 for ; offset < len(bytes); i++ {
231 v, offset, err = parseBase128Int(bytes, offset)
232 if err != nil {
233 return
235 s[i] = v
237 s = s[0:i]
238 return
241 // ENUMERATED
243 // An Enumerated is represented as a plain int.
244 type Enumerated int
246 // FLAG
248 // A Flag accepts any data and is set to true if present.
249 type Flag bool
251 // parseBase128Int parses a base-128 encoded int from the given offset in the
252 // given byte slice. It returns the value and the new offset.
253 func parseBase128Int(bytes []byte, initOffset int) (ret, offset int, err error) {
254 offset = initOffset
255 for shifted := 0; offset < len(bytes); shifted++ {
256 if shifted > 4 {
257 err = StructuralError{"base 128 integer too large"}
258 return
260 ret <<= 7
261 b := bytes[offset]
262 ret |= int(b & 0x7f)
263 offset++
264 if b&0x80 == 0 {
265 return
268 err = SyntaxError{"truncated base 128 integer"}
269 return
272 // UTCTime
274 func parseUTCTime(bytes []byte) (ret time.Time, err error) {
275 s := string(bytes)
276 ret, err = time.Parse("0601021504Z0700", s)
277 if err != nil {
278 ret, err = time.Parse("060102150405Z0700", s)
280 if err == nil && ret.Year() >= 2050 {
281 // UTCTime only encodes times prior to 2050. See https://tools.ietf.org/html/rfc5280#section-4.1.2.5.1
282 ret = ret.AddDate(-100, 0, 0)
285 return
288 // parseGeneralizedTime parses the GeneralizedTime from the given byte slice
289 // and returns the resulting time.
290 func parseGeneralizedTime(bytes []byte) (ret time.Time, err error) {
291 return time.Parse("20060102150405Z0700", string(bytes))
294 // PrintableString
296 // parsePrintableString parses a ASN.1 PrintableString from the given byte
297 // array and returns it.
298 func parsePrintableString(bytes []byte) (ret string, err error) {
299 for _, b := range bytes {
300 if !isPrintable(b) {
301 err = SyntaxError{"PrintableString contains invalid character"}
302 return
305 ret = string(bytes)
306 return
309 // isPrintable returns true iff the given b is in the ASN.1 PrintableString set.
310 func isPrintable(b byte) bool {
311 return 'a' <= b && b <= 'z' ||
312 'A' <= b && b <= 'Z' ||
313 '0' <= b && b <= '9' ||
314 '\'' <= b && b <= ')' ||
315 '+' <= b && b <= '/' ||
316 b == ' ' ||
317 b == ':' ||
318 b == '=' ||
319 b == '?' ||
320 // This is technically not allowed in a PrintableString.
321 // However, x509 certificates with wildcard strings don't
322 // always use the correct string type so we permit it.
323 b == '*'
326 // IA5String
328 // parseIA5String parses a ASN.1 IA5String (ASCII string) from the given
329 // byte slice and returns it.
330 func parseIA5String(bytes []byte) (ret string, err error) {
331 for _, b := range bytes {
332 if b >= 0x80 {
333 err = SyntaxError{"IA5String contains invalid character"}
334 return
337 ret = string(bytes)
338 return
341 // T61String
343 // parseT61String parses a ASN.1 T61String (8-bit clean string) from the given
344 // byte slice and returns it.
345 func parseT61String(bytes []byte) (ret string, err error) {
346 return string(bytes), nil
349 // UTF8String
351 // parseUTF8String parses a ASN.1 UTF8String (raw UTF-8) from the given byte
352 // array and returns it.
353 func parseUTF8String(bytes []byte) (ret string, err error) {
354 return string(bytes), nil
357 // A RawValue represents an undecoded ASN.1 object.
358 type RawValue struct {
359 Class, Tag int
360 IsCompound bool
361 Bytes []byte
362 FullBytes []byte // includes the tag and length
365 // RawContent is used to signal that the undecoded, DER data needs to be
366 // preserved for a struct. To use it, the first field of the struct must have
367 // this type. It's an error for any of the other fields to have this type.
368 type RawContent []byte
370 // Tagging
372 // parseTagAndLength parses an ASN.1 tag and length pair from the given offset
373 // into a byte slice. It returns the parsed data and the new offset. SET and
374 // SET OF (tag 17) are mapped to SEQUENCE and SEQUENCE OF (tag 16) since we
375 // don't distinguish between ordered and unordered objects in this code.
376 func parseTagAndLength(bytes []byte, initOffset int) (ret tagAndLength, offset int, err error) {
377 offset = initOffset
378 b := bytes[offset]
379 offset++
380 ret.class = int(b >> 6)
381 ret.isCompound = b&0x20 == 0x20
382 ret.tag = int(b & 0x1f)
384 // If the bottom five bits are set, then the tag number is actually base 128
385 // encoded afterwards
386 if ret.tag == 0x1f {
387 ret.tag, offset, err = parseBase128Int(bytes, offset)
388 if err != nil {
389 return
392 if offset >= len(bytes) {
393 err = SyntaxError{"truncated tag or length"}
394 return
396 b = bytes[offset]
397 offset++
398 if b&0x80 == 0 {
399 // The length is encoded in the bottom 7 bits.
400 ret.length = int(b & 0x7f)
401 } else {
402 // Bottom 7 bits give the number of length bytes to follow.
403 numBytes := int(b & 0x7f)
404 if numBytes == 0 {
405 err = SyntaxError{"indefinite length found (not DER)"}
406 return
408 ret.length = 0
409 for i := 0; i < numBytes; i++ {
410 if offset >= len(bytes) {
411 err = SyntaxError{"truncated tag or length"}
412 return
414 b = bytes[offset]
415 offset++
416 if ret.length >= 1<<23 {
417 // We can't shift ret.length up without
418 // overflowing.
419 err = StructuralError{"length too large"}
420 return
422 ret.length <<= 8
423 ret.length |= int(b)
424 if ret.length == 0 {
425 // DER requires that lengths be minimal.
426 err = StructuralError{"superfluous leading zeros in length"}
427 return
432 return
435 // parseSequenceOf is used for SEQUENCE OF and SET OF values. It tries to parse
436 // a number of ASN.1 values from the given byte slice and returns them as a
437 // slice of Go values of the given type.
438 func parseSequenceOf(bytes []byte, sliceType reflect.Type, elemType reflect.Type) (ret reflect.Value, err error) {
439 expectedTag, compoundType, ok := getUniversalType(elemType)
440 if !ok {
441 err = StructuralError{"unknown Go type for slice"}
442 return
445 // First we iterate over the input and count the number of elements,
446 // checking that the types are correct in each case.
447 numElements := 0
448 for offset := 0; offset < len(bytes); {
449 var t tagAndLength
450 t, offset, err = parseTagAndLength(bytes, offset)
451 if err != nil {
452 return
454 // We pretend that various other string types are PRINTABLE STRINGs
455 // so that a sequence of them can be parsed into a []string.
456 switch t.tag {
457 case tagIA5String, tagGeneralString, tagT61String, tagUTF8String:
458 t.tag = tagPrintableString
461 if t.class != classUniversal || t.isCompound != compoundType || t.tag != expectedTag {
462 err = StructuralError{"sequence tag mismatch"}
463 return
465 if invalidLength(offset, t.length, len(bytes)) {
466 err = SyntaxError{"truncated sequence"}
467 return
469 offset += t.length
470 numElements++
472 ret = reflect.MakeSlice(sliceType, numElements, numElements)
473 params := fieldParameters{}
474 offset := 0
475 for i := 0; i < numElements; i++ {
476 offset, err = parseField(ret.Index(i), bytes, offset, params)
477 if err != nil {
478 return
481 return
484 var (
485 bitStringType = reflect.TypeOf(BitString{})
486 objectIdentifierType = reflect.TypeOf(ObjectIdentifier{})
487 enumeratedType = reflect.TypeOf(Enumerated(0))
488 flagType = reflect.TypeOf(Flag(false))
489 timeType = reflect.TypeOf(time.Time{})
490 rawValueType = reflect.TypeOf(RawValue{})
491 rawContentsType = reflect.TypeOf(RawContent(nil))
492 bigIntType = reflect.TypeOf(new(big.Int))
495 // invalidLength returns true iff offset + length > sliceLength, or if the
496 // addition would overflow.
497 func invalidLength(offset, length, sliceLength int) bool {
498 return offset+length < offset || offset+length > sliceLength
501 // parseField is the main parsing function. Given a byte slice and an offset
502 // into the array, it will try to parse a suitable ASN.1 value out and store it
503 // in the given Value.
504 func parseField(v reflect.Value, bytes []byte, initOffset int, params fieldParameters) (offset int, err error) {
505 offset = initOffset
506 fieldType := v.Type()
508 // If we have run out of data, it may be that there are optional elements at the end.
509 if offset == len(bytes) {
510 if !setDefaultValue(v, params) {
511 err = SyntaxError{"sequence truncated"}
513 return
516 // Deal with raw values.
517 if fieldType == rawValueType {
518 var t tagAndLength
519 t, offset, err = parseTagAndLength(bytes, offset)
520 if err != nil {
521 return
523 if invalidLength(offset, t.length, len(bytes)) {
524 err = SyntaxError{"data truncated"}
525 return
527 result := RawValue{t.class, t.tag, t.isCompound, bytes[offset : offset+t.length], bytes[initOffset : offset+t.length]}
528 offset += t.length
529 v.Set(reflect.ValueOf(result))
530 return
533 // Deal with the ANY type.
534 if ifaceType := fieldType; ifaceType.Kind() == reflect.Interface && ifaceType.NumMethod() == 0 {
535 var t tagAndLength
536 t, offset, err = parseTagAndLength(bytes, offset)
537 if err != nil {
538 return
540 if invalidLength(offset, t.length, len(bytes)) {
541 err = SyntaxError{"data truncated"}
542 return
544 var result interface{}
545 if !t.isCompound && t.class == classUniversal {
546 innerBytes := bytes[offset : offset+t.length]
547 switch t.tag {
548 case tagPrintableString:
549 result, err = parsePrintableString(innerBytes)
550 case tagIA5String:
551 result, err = parseIA5String(innerBytes)
552 case tagT61String:
553 result, err = parseT61String(innerBytes)
554 case tagUTF8String:
555 result, err = parseUTF8String(innerBytes)
556 case tagInteger:
557 result, err = parseInt64(innerBytes)
558 case tagBitString:
559 result, err = parseBitString(innerBytes)
560 case tagOID:
561 result, err = parseObjectIdentifier(innerBytes)
562 case tagUTCTime:
563 result, err = parseUTCTime(innerBytes)
564 case tagOctetString:
565 result = innerBytes
566 default:
567 // If we don't know how to handle the type, we just leave Value as nil.
570 offset += t.length
571 if err != nil {
572 return
574 if result != nil {
575 v.Set(reflect.ValueOf(result))
577 return
579 universalTag, compoundType, ok1 := getUniversalType(fieldType)
580 if !ok1 {
581 err = StructuralError{fmt.Sprintf("unknown Go type: %v", fieldType)}
582 return
585 t, offset, err := parseTagAndLength(bytes, offset)
586 if err != nil {
587 return
589 if params.explicit {
590 expectedClass := classContextSpecific
591 if params.application {
592 expectedClass = classApplication
594 if t.class == expectedClass && t.tag == *params.tag && (t.length == 0 || t.isCompound) {
595 if t.length > 0 {
596 t, offset, err = parseTagAndLength(bytes, offset)
597 if err != nil {
598 return
600 } else {
601 if fieldType != flagType {
602 err = StructuralError{"zero length explicit tag was not an asn1.Flag"}
603 return
605 v.SetBool(true)
606 return
608 } else {
609 // The tags didn't match, it might be an optional element.
610 ok := setDefaultValue(v, params)
611 if ok {
612 offset = initOffset
613 } else {
614 err = StructuralError{"explicitly tagged member didn't match"}
616 return
620 // Special case for strings: all the ASN.1 string types map to the Go
621 // type string. getUniversalType returns the tag for PrintableString
622 // when it sees a string, so if we see a different string type on the
623 // wire, we change the universal type to match.
624 if universalTag == tagPrintableString {
625 switch t.tag {
626 case tagIA5String, tagGeneralString, tagT61String, tagUTF8String:
627 universalTag = t.tag
631 // Special case for time: UTCTime and GeneralizedTime both map to the
632 // Go type time.Time.
633 if universalTag == tagUTCTime && t.tag == tagGeneralizedTime {
634 universalTag = tagGeneralizedTime
637 expectedClass := classUniversal
638 expectedTag := universalTag
640 if !params.explicit && params.tag != nil {
641 expectedClass = classContextSpecific
642 expectedTag = *params.tag
645 if !params.explicit && params.application && params.tag != nil {
646 expectedClass = classApplication
647 expectedTag = *params.tag
650 // We have unwrapped any explicit tagging at this point.
651 if t.class != expectedClass || t.tag != expectedTag || t.isCompound != compoundType {
652 // Tags don't match. Again, it could be an optional element.
653 ok := setDefaultValue(v, params)
654 if ok {
655 offset = initOffset
656 } else {
657 err = StructuralError{fmt.Sprintf("tags don't match (%d vs %+v) %+v %s @%d", expectedTag, t, params, fieldType.Name(), offset)}
659 return
661 if invalidLength(offset, t.length, len(bytes)) {
662 err = SyntaxError{"data truncated"}
663 return
665 innerBytes := bytes[offset : offset+t.length]
666 offset += t.length
668 // We deal with the structures defined in this package first.
669 switch fieldType {
670 case objectIdentifierType:
671 newSlice, err1 := parseObjectIdentifier(innerBytes)
672 v.Set(reflect.MakeSlice(v.Type(), len(newSlice), len(newSlice)))
673 if err1 == nil {
674 reflect.Copy(v, reflect.ValueOf(newSlice))
676 err = err1
677 return
678 case bitStringType:
679 bs, err1 := parseBitString(innerBytes)
680 if err1 == nil {
681 v.Set(reflect.ValueOf(bs))
683 err = err1
684 return
685 case timeType:
686 var time time.Time
687 var err1 error
688 if universalTag == tagUTCTime {
689 time, err1 = parseUTCTime(innerBytes)
690 } else {
691 time, err1 = parseGeneralizedTime(innerBytes)
693 if err1 == nil {
694 v.Set(reflect.ValueOf(time))
696 err = err1
697 return
698 case enumeratedType:
699 parsedInt, err1 := parseInt32(innerBytes)
700 if err1 == nil {
701 v.SetInt(int64(parsedInt))
703 err = err1
704 return
705 case flagType:
706 v.SetBool(true)
707 return
708 case bigIntType:
709 parsedInt := parseBigInt(innerBytes)
710 v.Set(reflect.ValueOf(parsedInt))
711 return
713 switch val := v; val.Kind() {
714 case reflect.Bool:
715 parsedBool, err1 := parseBool(innerBytes)
716 if err1 == nil {
717 val.SetBool(parsedBool)
719 err = err1
720 return
721 case reflect.Int, reflect.Int32, reflect.Int64:
722 if val.Type().Size() == 4 {
723 parsedInt, err1 := parseInt32(innerBytes)
724 if err1 == nil {
725 val.SetInt(int64(parsedInt))
727 err = err1
728 } else {
729 parsedInt, err1 := parseInt64(innerBytes)
730 if err1 == nil {
731 val.SetInt(parsedInt)
733 err = err1
735 return
736 // TODO(dfc) Add support for the remaining integer types
737 case reflect.Struct:
738 structType := fieldType
740 if structType.NumField() > 0 &&
741 structType.Field(0).Type == rawContentsType {
742 bytes := bytes[initOffset:offset]
743 val.Field(0).Set(reflect.ValueOf(RawContent(bytes)))
746 innerOffset := 0
747 for i := 0; i < structType.NumField(); i++ {
748 field := structType.Field(i)
749 if i == 0 && field.Type == rawContentsType {
750 continue
752 innerOffset, err = parseField(val.Field(i), innerBytes, innerOffset, parseFieldParameters(field.Tag.Get("asn1")))
753 if err != nil {
754 return
757 // We allow extra bytes at the end of the SEQUENCE because
758 // adding elements to the end has been used in X.509 as the
759 // version numbers have increased.
760 return
761 case reflect.Slice:
762 sliceType := fieldType
763 if sliceType.Elem().Kind() == reflect.Uint8 {
764 val.Set(reflect.MakeSlice(sliceType, len(innerBytes), len(innerBytes)))
765 reflect.Copy(val, reflect.ValueOf(innerBytes))
766 return
768 newSlice, err1 := parseSequenceOf(innerBytes, sliceType, sliceType.Elem())
769 if err1 == nil {
770 val.Set(newSlice)
772 err = err1
773 return
774 case reflect.String:
775 var v string
776 switch universalTag {
777 case tagPrintableString:
778 v, err = parsePrintableString(innerBytes)
779 case tagIA5String:
780 v, err = parseIA5String(innerBytes)
781 case tagT61String:
782 v, err = parseT61String(innerBytes)
783 case tagUTF8String:
784 v, err = parseUTF8String(innerBytes)
785 case tagGeneralString:
786 // GeneralString is specified in ISO-2022/ECMA-35,
787 // A brief review suggests that it includes structures
788 // that allow the encoding to change midstring and
789 // such. We give up and pass it as an 8-bit string.
790 v, err = parseT61String(innerBytes)
791 default:
792 err = SyntaxError{fmt.Sprintf("internal error: unknown string type %d", universalTag)}
794 if err == nil {
795 val.SetString(v)
797 return
799 err = StructuralError{"unsupported: " + v.Type().String()}
800 return
803 // setDefaultValue is used to install a default value, from a tag string, into
804 // a Value. It is successful is the field was optional, even if a default value
805 // wasn't provided or it failed to install it into the Value.
806 func setDefaultValue(v reflect.Value, params fieldParameters) (ok bool) {
807 if !params.optional {
808 return
810 ok = true
811 if params.defaultValue == nil {
812 return
814 switch val := v; val.Kind() {
815 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
816 val.SetInt(*params.defaultValue)
818 return
821 // Unmarshal parses the DER-encoded ASN.1 data structure b
822 // and uses the reflect package to fill in an arbitrary value pointed at by val.
823 // Because Unmarshal uses the reflect package, the structs
824 // being written to must use upper case field names.
826 // An ASN.1 INTEGER can be written to an int, int32, int64,
827 // or *big.Int (from the math/big package).
828 // If the encoded value does not fit in the Go type,
829 // Unmarshal returns a parse error.
831 // An ASN.1 BIT STRING can be written to a BitString.
833 // An ASN.1 OCTET STRING can be written to a []byte.
835 // An ASN.1 OBJECT IDENTIFIER can be written to an
836 // ObjectIdentifier.
838 // An ASN.1 ENUMERATED can be written to an Enumerated.
840 // An ASN.1 UTCTIME or GENERALIZEDTIME can be written to a time.Time.
842 // An ASN.1 PrintableString or IA5String can be written to a string.
844 // Any of the above ASN.1 values can be written to an interface{}.
845 // The value stored in the interface has the corresponding Go type.
846 // For integers, that type is int64.
848 // An ASN.1 SEQUENCE OF x or SET OF x can be written
849 // to a slice if an x can be written to the slice's element type.
851 // An ASN.1 SEQUENCE or SET can be written to a struct
852 // if each of the elements in the sequence can be
853 // written to the corresponding element in the struct.
855 // The following tags on struct fields have special meaning to Unmarshal:
857 // optional marks the field as ASN.1 OPTIONAL
858 // [explicit] tag:x specifies the ASN.1 tag number; implies ASN.1 CONTEXT SPECIFIC
859 // default:x sets the default value for optional integer fields
861 // If the type of the first field of a structure is RawContent then the raw
862 // ASN1 contents of the struct will be stored in it.
864 // Other ASN.1 types are not supported; if it encounters them,
865 // Unmarshal returns a parse error.
866 func Unmarshal(b []byte, val interface{}) (rest []byte, err error) {
867 return UnmarshalWithParams(b, val, "")
870 // UnmarshalWithParams allows field parameters to be specified for the
871 // top-level element. The form of the params is the same as the field tags.
872 func UnmarshalWithParams(b []byte, val interface{}, params string) (rest []byte, err error) {
873 v := reflect.ValueOf(val).Elem()
874 offset, err := parseField(v, b, 0, parseFieldParameters(params))
875 if err != nil {
876 return nil, err
878 return b[offset:], nil