1 // Copyright 2017 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.
15 // This file contains ASN.1-related methods for String and Builder.
17 // Tag represents an ASN.1 tag number and class (together also referred to as
18 // identifier octets). Methods in this package only support the low-tag-number
19 // form, i.e. a single identifier octet with bits 7-8 encoding the class and
20 // bits 1-6 encoding the tag number.
23 // Contructed returns t with the context-specific class bit set.
24 func (t Tag) ContextSpecific() Tag { return t | 0x80 }
26 // Contructed returns t with the constructed class bit set.
27 func (t Tag) Constructed() Tag { return t | 0x20 }
31 // AddASN1Int64 appends a DER-encoded ASN.1 INTEGER.
32 func (b *Builder) AddASN1Int64(v int64) {
33 b.addASN1Signed(asn1.TagInteger, v)
36 // AddASN1Enum appends a DER-encoded ASN.1 ENUMERATION.
37 func (b *Builder) AddASN1Enum(v int64) {
38 b.addASN1Signed(asn1.TagEnum, v)
41 func (b *Builder) addASN1Signed(tag Tag, v int64) {
42 b.AddASN1(tag, func(c *Builder) {
44 for i := v; i >= 0x80 || i < -0x80; i >>= 8 {
48 for ; length > 0; length-- {
49 i := v >> uint((length-1)*8) & 0xff
55 // AddASN1Uint64 appends a DER-encoded ASN.1 INTEGER.
56 func (b *Builder) AddASN1Uint64(v uint64) {
57 b.AddASN1(asn1.TagInteger, func(c *Builder) {
59 for i := v; i >= 0x80; i >>= 8 {
63 for ; length > 0; length-- {
64 i := v >> uint((length-1)*8) & 0xff
70 // AddASN1BigInt appends a DER-encoded ASN.1 INTEGER.
71 func (b *Builder) AddASN1BigInt(n *big.Int) {
76 b.AddASN1(asn1.TagInteger, func(c *Builder) {
78 // A negative number has to be converted to two's-complement form. So we
79 // invert and subtract 1. If the most-significant-bit isn't set then
80 // we'll need to pad the beginning with 0xff in order to keep the number
82 nMinus1 := new(big.Int).Neg(n)
83 nMinus1.Sub(nMinus1, bigOne)
84 bytes := nMinus1.Bytes()
85 for i := range bytes {
88 if bytes[0]&0x80 == 0 {
92 } else if n.Sign() == 0 {
96 if bytes[0]&0x80 != 0 {
104 // AddASN1OctetString appends a DER-encoded ASN.1 OCTET STRING.
105 func (b *Builder) AddASN1OctetString(bytes []byte) {
106 b.AddASN1(asn1.TagOctetString, func(c *Builder) {
111 const generalizedTimeFormatStr = "20060102150405Z0700"
113 // AddASN1GeneralizedTime appends a DER-encoded ASN.1 GENERALIZEDTIME.
114 func (b *Builder) AddASN1GeneralizedTime(t time.Time) {
115 if t.Year() < 0 || t.Year() > 9999 {
116 b.err = fmt.Errorf("cryptobyte: cannot represent %v as a GeneralizedTime", t)
119 b.AddASN1(asn1.TagGeneralizedTime, func(c *Builder) {
120 c.AddBytes([]byte(t.Format(generalizedTimeFormatStr)))
124 // AddASN1BitString appends a DER-encoded ASN.1 BIT STRING.
125 func (b *Builder) AddASN1BitString(s asn1.BitString) {
126 // TODO(martinkr): Implement.
130 // MarshalASN1 calls asn1.Marshal on its input and appends the result if
131 // successful or records an error if one occurred.
132 func (b *Builder) MarshalASN1(v interface{}) {
133 // NOTE(martinkr): This is somewhat of a hack to allow propagation of
134 // asn1.Marshal errors into Builder.err. N.B. if you call MarshalASN1 with a
135 // value embedded into a struct, its tag information is lost.
139 bytes, err := asn1.Marshal(v)
147 // AddASN1 appends an ASN.1 object. The object is prefixed with the given tag.
148 // Tags greater than 30 are not supported and result in an error (i.e.
149 // low-tag-number form only). The child builder passed to the
150 // BuilderContinuation can be used to build the content of the ASN.1 object.
151 func (b *Builder) AddASN1(tag Tag, f BuilderContinuation) {
155 // Identifiers with the low five bits set indicate high-tag-number format
156 // (two or more octets), which we don't support.
157 if tag&0x1f == 0x1f {
158 b.err = fmt.Errorf("cryptobyte: high-tag number identifier octects not supported: 0x%x", tag)
161 b.AddUint8(uint8(tag))
162 b.addLengthPrefixed(1, true, f)
167 var bigIntType = reflect.TypeOf((*big.Int)(nil)).Elem()
169 // ReadASN1Integer decodes an ASN.1 INTEGER into out and advances. If out does
170 // not point to an integer or to a big.Int, it panics. It returns true on
171 // success and false on error.
172 func (s *String) ReadASN1Integer(out interface{}) bool {
173 if reflect.TypeOf(out).Kind() != reflect.Ptr {
174 panic("out is not a pointer")
176 switch reflect.ValueOf(out).Elem().Kind() {
177 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
179 if !s.readASN1Int64(&i) || reflect.ValueOf(out).Elem().OverflowInt(i) {
182 reflect.ValueOf(out).Elem().SetInt(i)
184 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
186 if !s.readASN1Uint64(&u) || reflect.ValueOf(out).Elem().OverflowUint(u) {
189 reflect.ValueOf(out).Elem().SetUint(u)
192 if reflect.TypeOf(out).Elem() == bigIntType {
193 return s.readASN1BigInt(out.(*big.Int))
196 panic("out does not point to an integer type")
199 func checkASN1Integer(bytes []byte) bool {
201 // An INTEGER is encoded with at least one octet.
207 if bytes[0] == 0 && bytes[1]&0x80 == 0 || bytes[0] == 0xff && bytes[1]&0x80 == 0x80 {
208 // Value is not minimally encoded.
214 var bigOne = big.NewInt(1)
216 func (s *String) readASN1BigInt(out *big.Int) bool {
218 if !s.ReadASN1(&bytes, asn1.TagInteger) || !checkASN1Integer(bytes) {
221 if bytes[0]&0x80 == 0x80 {
223 neg := make([]byte, len(bytes))
224 for i, b := range bytes {
236 func (s *String) readASN1Int64(out *int64) bool {
238 if !s.ReadASN1(&bytes, asn1.TagInteger) || !checkASN1Integer(bytes) || !asn1Signed(out, bytes) {
244 func asn1Signed(out *int64, n []byte) bool {
249 for i := 0; i < length; i++ {
253 // Shift up and down in order to sign extend the result.
254 *out <<= 64 - uint8(length)*8
255 *out >>= 64 - uint8(length)*8
259 func (s *String) readASN1Uint64(out *uint64) bool {
261 if !s.ReadASN1(&bytes, asn1.TagInteger) || !checkASN1Integer(bytes) || !asn1Unsigned(out, bytes) {
267 func asn1Unsigned(out *uint64, n []byte) bool {
269 if length > 9 || length == 9 && n[0] != 0 {
270 // Too large for uint64.
277 for i := 0; i < length; i++ {
284 // ReadASN1Enum decodes an ASN.1 ENUMERATION into out and advances. It returns
285 // true on success and false on error.
286 func (s *String) ReadASN1Enum(out *int) bool {
289 if !s.ReadASN1(&bytes, asn1.TagEnum) || !checkASN1Integer(bytes) || !asn1Signed(&i, bytes) {
292 if int64(int(i)) != i {
299 func (s *String) readBase128Int(out *int) bool {
301 for i := 0; len(*s) > 0; i++ {
313 return false // truncated
316 // ReadASN1ObjectIdentifier decodes an ASN.1 OBJECT IDENTIFIER into out and
317 // advances. It returns true on success and false on error.
318 func (s *String) ReadASN1ObjectIdentifier(out *asn1.ObjectIdentifier) bool {
320 if !s.ReadASN1(&bytes, asn1.TagOID) || len(bytes) == 0 {
324 // In the worst case, we get two elements from the first byte (which is
325 // encoded differently) and then every varint is a single byte long.
326 components := make([]int, len(bytes)+1)
328 // The first varint is 40*value1 + value2:
329 // According to this packing, value1 can take the values 0, 1 and 2 only.
330 // When value1 = 0 or value1 = 1, then value2 is <= 39. When value1 = 2,
331 // then there are no restrictions on value2.
333 if !bytes.readBase128Int(&v) {
337 components[0] = v / 40
338 components[1] = v % 40
341 components[1] = v - 80
345 for ; len(bytes) > 0; i++ {
346 if !bytes.readBase128Int(&v) {
351 *out = components[:i]
355 // ReadASN1GeneralizedTime decodes an ASN.1 GENERALIZEDTIME into out and
356 // advances. It returns true on success and false on error.
357 func (s *String) ReadASN1GeneralizedTime(out *time.Time) bool {
359 if !s.ReadASN1(&bytes, asn1.TagGeneralizedTime) {
363 res, err := time.Parse(generalizedTimeFormatStr, t)
367 if serialized := res.Format(generalizedTimeFormatStr); serialized != t {
374 // ReadASN1BitString decodes an ASN.1 BIT STRING into out and advances. It
375 // returns true on success and false on error.
376 func (s *String) ReadASN1BitString(out *asn1.BitString) bool {
378 if !s.ReadASN1(&bytes, asn1.TagBitString) || len(bytes) == 0 {
382 paddingBits := uint8(bytes[0])
384 if paddingBits > 7 ||
385 len(bytes) == 0 && paddingBits != 0 ||
386 len(bytes) > 0 && bytes[len(bytes)-1]&(1<<paddingBits-1) != 0 {
390 out.BitLength = len(bytes)*8 - int(paddingBits)
395 // ReadASN1Bytes reads the contents of a DER-encoded ASN.1 element (not including
396 // tag and length bytes) into out, and advances. The element must match the
397 // given tag. It returns true on success and false on error.
398 func (s *String) ReadASN1Bytes(out *[]byte, tag Tag) bool {
399 return s.ReadASN1((*String)(out), tag)
402 // ReadASN1 reads the contents of a DER-encoded ASN.1 element (not including
403 // tag and length bytes) into out, and advances. The element must match the
404 // given tag. It returns true on success and false on error.
406 // Tags greater than 30 are not supported (i.e. low-tag-number format only).
407 func (s *String) ReadASN1(out *String, tag Tag) bool {
409 if !s.ReadAnyASN1(out, &t) || t != tag {
415 // ReadASN1Element reads the contents of a DER-encoded ASN.1 element (including
416 // tag and length bytes) into out, and advances. The element must match the
417 // given tag. It returns true on success and false on error.
419 // Tags greater than 30 are not supported (i.e. low-tag-number format only).
420 func (s *String) ReadASN1Element(out *String, tag Tag) bool {
422 if !s.ReadAnyASN1Element(out, &t) || t != tag {
428 // ReadAnyASN1 reads the contents of a DER-encoded ASN.1 element (not including
429 // tag and length bytes) into out, sets outTag to its tag, and advances. It
430 // returns true on success and false on error.
432 // Tags greater than 30 are not supported (i.e. low-tag-number format only).
433 func (s *String) ReadAnyASN1(out *String, outTag *Tag) bool {
434 return s.readASN1(out, outTag, true /* skip header */)
437 // ReadAnyASN1Element reads the contents of a DER-encoded ASN.1 element
438 // (including tag and length bytes) into out, sets outTag to is tag, and
439 // advances. It returns true on success and false on error.
441 // Tags greater than 30 are not supported (i.e. low-tag-number format only).
442 func (s *String) ReadAnyASN1Element(out *String, outTag *Tag) bool {
443 return s.readASN1(out, outTag, false /* include header */)
446 // PeekASN1Tag returns true if the next ASN.1 value on the string starts with
448 func (s String) PeekASN1Tag(tag Tag) bool {
452 return Tag(s[0]) == tag
455 // ReadOptionalASN1 attempts to read the contents of a DER-encoded ASN.Element
456 // (not including tag and length bytes) tagged with the given tag into out. It
457 // stores whether an element with the tag was found in outPresent, unless
458 // outPresent is nil. It returns true on success and false on error.
459 func (s *String) ReadOptionalASN1(out *String, outPresent *bool, tag Tag) bool {
460 present := s.PeekASN1Tag(tag)
461 if outPresent != nil {
462 *outPresent = present
464 if present && !s.ReadASN1(out, tag) {
470 // ReadOptionalASN1Integer attempts to read an optional ASN.1 INTEGER
471 // explicitly tagged with tag into out and advances. If no element with a
472 // matching tag is present, it writes defaultValue into out instead. If out
473 // does not point to an integer or to a big.Int, it panics. It returns true on
474 // success and false on error.
475 func (s *String) ReadOptionalASN1Integer(out interface{}, tag Tag, defaultValue interface{}) bool {
476 if reflect.TypeOf(out).Kind() != reflect.Ptr {
477 panic("out is not a pointer")
481 if !s.ReadOptionalASN1(&i, &present, tag) {
485 switch reflect.ValueOf(out).Elem().Kind() {
486 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
487 reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
488 reflect.ValueOf(out).Elem().Set(reflect.ValueOf(defaultValue))
490 if reflect.TypeOf(out).Elem() != bigIntType {
491 panic("invalid integer type")
493 if reflect.TypeOf(defaultValue).Kind() != reflect.Ptr ||
494 reflect.TypeOf(defaultValue).Elem() != bigIntType {
495 panic("out points to big.Int, but defaultValue does not")
497 out.(*big.Int).Set(defaultValue.(*big.Int))
499 panic("invalid integer type")
503 if !i.ReadASN1Integer(out) || !i.Empty() {
509 // ReadOptionalASN1OctetString attempts to read an optional ASN.1 OCTET STRING
510 // explicitly tagged with tag into out and advances. If no element with a
511 // matching tag is present, it writes defaultValue into out instead. It returns
512 // true on success and false on error.
513 func (s *String) ReadOptionalASN1OctetString(out *[]byte, outPresent *bool, tag Tag) bool {
516 if !s.ReadOptionalASN1(&child, &present, tag) {
519 if outPresent != nil {
520 *outPresent = present
524 if !child.ReadASN1(&oct, asn1.TagOctetString) || !child.Empty() {
534 func (s *String) readASN1(out *String, outTag *Tag, skipHeader bool) bool {
538 tag, lenByte := (*s)[0], (*s)[1]
540 if tag&0x1f == 0x1f {
541 // ITU-T X.690 section 8.1.2
543 // An identifier octet with a tag part of 0x1f indicates a high-tag-number
544 // form identifier with two or more octets. We only support tags less than
545 // 31 (i.e. low-tag-number form, single octet identifier).
553 // ITU-T X.690 section 8.1.3
555 // Bit 8 of the first length byte indicates whether the length is short- or
557 var length, headerLen uint32 // length includes headerLen
558 if lenByte&0x80 == 0 {
559 // Short-form length (section 8.1.3.4), encoded in bits 1-7.
560 length = uint32(lenByte) + 2
563 // Long-form length (section 8.1.3.5). Bits 1-7 encode the number of octets
564 // used to encode the length.
565 lenLen := lenByte & 0x7f
568 if lenLen == 0 || lenLen > 4 || len(*s) < int(2+lenLen) {
572 lenBytes := String((*s)[2 : 2+lenLen])
573 if !lenBytes.readUnsigned(&len32, int(lenLen)) {
577 // ITU-T X.690 section 10.1 (DER length forms) requires encoding the length
578 // with the minimum number of octets.
580 // Length should have used short-form encoding.
583 if len32>>((lenLen-1)*8) == 0 {
584 // Leading octet is 0. Length should have been at least one byte shorter.
588 headerLen = 2 + uint32(lenLen)
589 if headerLen+len32 < len32 {
593 length = headerLen + len32
596 if uint32(int(length)) != length || !s.ReadBytes((*[]byte)(out), int(length)) {
599 if skipHeader && !out.Skip(int(headerLen)) {
600 panic("cryptobyte: internal error")