github.com/zmap/zcrypto@v0.0.0-20240512203510-0fef58d9a9db/cryptobyte/asn1.go (about)

     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.
     4  
     5  package cryptobyte
     6  
     7  import (
     8  	"fmt"
     9  	"math/big"
    10  	"reflect"
    11  	"time"
    12  
    13  	"github.com/zmap/zcrypto/cryptobyte/asn1"
    14  	encoding_asn1 "github.com/zmap/zcrypto/encoding/asn1"
    15  )
    16  
    17  // This file contains ASN.1-related methods for String and Builder.
    18  
    19  // Builder
    20  
    21  // AddASN1Int64 appends a DER-encoded ASN.1 INTEGER.
    22  func (b *Builder) AddASN1Int64(v int64) {
    23  	b.addASN1Signed(asn1.INTEGER, v)
    24  }
    25  
    26  // AddASN1Int64WithTag appends a DER-encoded ASN.1 INTEGER with the
    27  // given tag.
    28  func (b *Builder) AddASN1Int64WithTag(v int64, tag asn1.Tag) {
    29  	b.addASN1Signed(tag, v)
    30  }
    31  
    32  // AddASN1Enum appends a DER-encoded ASN.1 ENUMERATION.
    33  func (b *Builder) AddASN1Enum(v int64) {
    34  	b.addASN1Signed(asn1.ENUM, v)
    35  }
    36  
    37  func (b *Builder) addASN1Signed(tag asn1.Tag, v int64) {
    38  	b.AddASN1(tag, func(c *Builder) {
    39  		length := 1
    40  		for i := v; i >= 0x80 || i < -0x80; i >>= 8 {
    41  			length++
    42  		}
    43  
    44  		for ; length > 0; length-- {
    45  			i := v >> uint((length-1)*8) & 0xff
    46  			c.AddUint8(uint8(i))
    47  		}
    48  	})
    49  }
    50  
    51  // AddASN1Uint64 appends a DER-encoded ASN.1 INTEGER.
    52  func (b *Builder) AddASN1Uint64(v uint64) {
    53  	b.AddASN1(asn1.INTEGER, func(c *Builder) {
    54  		length := 1
    55  		for i := v; i >= 0x80; i >>= 8 {
    56  			length++
    57  		}
    58  
    59  		for ; length > 0; length-- {
    60  			i := v >> uint((length-1)*8) & 0xff
    61  			c.AddUint8(uint8(i))
    62  		}
    63  	})
    64  }
    65  
    66  // AddASN1BigInt appends a DER-encoded ASN.1 INTEGER.
    67  func (b *Builder) AddASN1BigInt(n *big.Int) {
    68  	if b.err != nil {
    69  		return
    70  	}
    71  
    72  	b.AddASN1(asn1.INTEGER, func(c *Builder) {
    73  		if n.Sign() < 0 {
    74  			// A negative number has to be converted to two's-complement form. So we
    75  			// invert and subtract 1. If the most-significant-bit isn't set then
    76  			// we'll need to pad the beginning with 0xff in order to keep the number
    77  			// negative.
    78  			nMinus1 := new(big.Int).Neg(n)
    79  			nMinus1.Sub(nMinus1, bigOne)
    80  			bytes := nMinus1.Bytes()
    81  			for i := range bytes {
    82  				bytes[i] ^= 0xff
    83  			}
    84  			if len(bytes) == 0 || bytes[0]&0x80 == 0 {
    85  				c.add(0xff)
    86  			}
    87  			c.add(bytes...)
    88  		} else if n.Sign() == 0 {
    89  			c.add(0)
    90  		} else {
    91  			bytes := n.Bytes()
    92  			if bytes[0]&0x80 != 0 {
    93  				c.add(0)
    94  			}
    95  			c.add(bytes...)
    96  		}
    97  	})
    98  }
    99  
   100  // AddASN1OctetString appends a DER-encoded ASN.1 OCTET STRING.
   101  func (b *Builder) AddASN1OctetString(bytes []byte) {
   102  	b.AddASN1(asn1.OCTET_STRING, func(c *Builder) {
   103  		c.AddBytes(bytes)
   104  	})
   105  }
   106  
   107  const generalizedTimeFormatStr = "20060102150405Z0700"
   108  
   109  // AddASN1GeneralizedTime appends a DER-encoded ASN.1 GENERALIZEDTIME.
   110  func (b *Builder) AddASN1GeneralizedTime(t time.Time) {
   111  	if t.Year() < 0 || t.Year() > 9999 {
   112  		b.err = fmt.Errorf("cryptobyte: cannot represent %v as a GeneralizedTime", t)
   113  		return
   114  	}
   115  	b.AddASN1(asn1.GeneralizedTime, func(c *Builder) {
   116  		c.AddBytes([]byte(t.Format(generalizedTimeFormatStr)))
   117  	})
   118  }
   119  
   120  // AddASN1BitString appends a DER-encoded ASN.1 BIT STRING. This does not
   121  // support BIT STRINGs that are not a whole number of bytes.
   122  func (b *Builder) AddASN1BitString(data []byte) {
   123  	b.AddASN1(asn1.BIT_STRING, func(b *Builder) {
   124  		b.AddUint8(0)
   125  		b.AddBytes(data)
   126  	})
   127  }
   128  
   129  func (b *Builder) addBase128Int(n int64) {
   130  	var length int
   131  	if n == 0 {
   132  		length = 1
   133  	} else {
   134  		for i := n; i > 0; i >>= 7 {
   135  			length++
   136  		}
   137  	}
   138  
   139  	for i := length - 1; i >= 0; i-- {
   140  		o := byte(n >> uint(i*7))
   141  		o &= 0x7f
   142  		if i != 0 {
   143  			o |= 0x80
   144  		}
   145  
   146  		b.add(o)
   147  	}
   148  }
   149  
   150  func isValidOID(oid encoding_asn1.ObjectIdentifier) bool {
   151  	if len(oid) < 2 {
   152  		return false
   153  	}
   154  
   155  	if oid[0] > 2 || (oid[0] <= 1 && oid[1] >= 40) {
   156  		return false
   157  	}
   158  
   159  	for _, v := range oid {
   160  		if v < 0 {
   161  			return false
   162  		}
   163  	}
   164  
   165  	return true
   166  }
   167  
   168  func (b *Builder) AddASN1ObjectIdentifier(oid encoding_asn1.ObjectIdentifier) {
   169  	b.AddASN1(asn1.OBJECT_IDENTIFIER, func(b *Builder) {
   170  		if !isValidOID(oid) {
   171  			b.err = fmt.Errorf("cryptobyte: invalid OID: %v", oid)
   172  			return
   173  		}
   174  
   175  		b.addBase128Int(int64(oid[0])*40 + int64(oid[1]))
   176  		for _, v := range oid[2:] {
   177  			b.addBase128Int(int64(v))
   178  		}
   179  	})
   180  }
   181  
   182  func (b *Builder) AddASN1Boolean(v bool) {
   183  	b.AddASN1(asn1.BOOLEAN, func(b *Builder) {
   184  		if v {
   185  			b.AddUint8(0xff)
   186  		} else {
   187  			b.AddUint8(0)
   188  		}
   189  	})
   190  }
   191  
   192  func (b *Builder) AddASN1NULL() {
   193  	b.add(uint8(asn1.NULL), 0)
   194  }
   195  
   196  // MarshalASN1 calls encoding_asn1.Marshal on its input and appends the result if
   197  // successful or records an error if one occurred.
   198  func (b *Builder) MarshalASN1(v interface{}) {
   199  	// NOTE(martinkr): This is somewhat of a hack to allow propagation of
   200  	// encoding_asn1.Marshal errors into Builder.err. N.B. if you call MarshalASN1 with a
   201  	// value embedded into a struct, its tag information is lost.
   202  	if b.err != nil {
   203  		return
   204  	}
   205  	bytes, err := encoding_asn1.Marshal(v)
   206  	if err != nil {
   207  		b.err = err
   208  		return
   209  	}
   210  	b.AddBytes(bytes)
   211  }
   212  
   213  // AddASN1 appends an ASN.1 object. The object is prefixed with the given tag.
   214  // Tags greater than 30 are not supported and result in an error (i.e.
   215  // low-tag-number form only). The child builder passed to the
   216  // BuilderContinuation can be used to build the content of the ASN.1 object.
   217  func (b *Builder) AddASN1(tag asn1.Tag, f BuilderContinuation) {
   218  	if b.err != nil {
   219  		return
   220  	}
   221  	// Identifiers with the low five bits set indicate high-tag-number format
   222  	// (two or more octets), which we don't support.
   223  	if tag&0x1f == 0x1f {
   224  		b.err = fmt.Errorf("cryptobyte: high-tag number identifier octects not supported: 0x%x", tag)
   225  		return
   226  	}
   227  	b.AddUint8(uint8(tag))
   228  	b.addLengthPrefixed(1, true, f)
   229  }
   230  
   231  // String
   232  
   233  // ReadASN1Boolean decodes an ASN.1 BOOLEAN and converts it to a boolean
   234  // representation into out and advances. It reports whether the read
   235  // was successful.
   236  func (s *String) ReadASN1Boolean(out *bool) bool {
   237  	var bytes String
   238  	if !s.ReadASN1(&bytes, asn1.BOOLEAN) || len(bytes) != 1 {
   239  		return false
   240  	}
   241  
   242  	switch bytes[0] {
   243  	case 0:
   244  		*out = false
   245  	case 0xff:
   246  		*out = true
   247  	default:
   248  		return false
   249  	}
   250  
   251  	return true
   252  }
   253  
   254  var bigIntType = reflect.TypeOf((*big.Int)(nil)).Elem()
   255  
   256  // ReadASN1Integer decodes an ASN.1 INTEGER into out and advances. If out does
   257  // not point to an integer or to a big.Int, it panics. It reports whether the
   258  // read was successful.
   259  func (s *String) ReadASN1Integer(out interface{}) bool {
   260  	if reflect.TypeOf(out).Kind() != reflect.Ptr {
   261  		panic("out is not a pointer")
   262  	}
   263  	switch reflect.ValueOf(out).Elem().Kind() {
   264  	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
   265  		var i int64
   266  		if !s.readASN1Int64(&i) || reflect.ValueOf(out).Elem().OverflowInt(i) {
   267  			return false
   268  		}
   269  		reflect.ValueOf(out).Elem().SetInt(i)
   270  		return true
   271  	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
   272  		var u uint64
   273  		if !s.readASN1Uint64(&u) || reflect.ValueOf(out).Elem().OverflowUint(u) {
   274  			return false
   275  		}
   276  		reflect.ValueOf(out).Elem().SetUint(u)
   277  		return true
   278  	case reflect.Struct:
   279  		if reflect.TypeOf(out).Elem() == bigIntType {
   280  			return s.readASN1BigInt(out.(*big.Int))
   281  		}
   282  	}
   283  	panic("out does not point to an integer type")
   284  }
   285  
   286  func checkASN1Integer(bytes []byte) bool {
   287  	if len(bytes) == 0 {
   288  		// An INTEGER is encoded with at least one octet.
   289  		return false
   290  	}
   291  	if len(bytes) == 1 {
   292  		return true
   293  	}
   294  	if bytes[0] == 0 && bytes[1]&0x80 == 0 || bytes[0] == 0xff && bytes[1]&0x80 == 0x80 {
   295  		// Value is not minimally encoded.
   296  		return false
   297  	}
   298  	return true
   299  }
   300  
   301  var bigOne = big.NewInt(1)
   302  
   303  func (s *String) readASN1BigInt(out *big.Int) bool {
   304  	var bytes String
   305  	if !s.ReadASN1(&bytes, asn1.INTEGER) || !checkASN1Integer(bytes) {
   306  		return false
   307  	}
   308  	if bytes[0]&0x80 == 0x80 {
   309  		// Negative number.
   310  		neg := make([]byte, len(bytes))
   311  		for i, b := range bytes {
   312  			neg[i] = ^b
   313  		}
   314  		out.SetBytes(neg)
   315  		out.Add(out, bigOne)
   316  		out.Neg(out)
   317  	} else {
   318  		out.SetBytes(bytes)
   319  	}
   320  	return true
   321  }
   322  
   323  func (s *String) readASN1Int64(out *int64) bool {
   324  	var bytes String
   325  	if !s.ReadASN1(&bytes, asn1.INTEGER) || !checkASN1Integer(bytes) || !asn1Signed(out, bytes) {
   326  		return false
   327  	}
   328  	return true
   329  }
   330  
   331  func asn1Signed(out *int64, n []byte) bool {
   332  	length := len(n)
   333  	if length > 8 {
   334  		return false
   335  	}
   336  	for i := 0; i < length; i++ {
   337  		*out <<= 8
   338  		*out |= int64(n[i])
   339  	}
   340  	// Shift up and down in order to sign extend the result.
   341  	*out <<= 64 - uint8(length)*8
   342  	*out >>= 64 - uint8(length)*8
   343  	return true
   344  }
   345  
   346  func (s *String) readASN1Uint64(out *uint64) bool {
   347  	var bytes String
   348  	if !s.ReadASN1(&bytes, asn1.INTEGER) || !checkASN1Integer(bytes) || !asn1Unsigned(out, bytes) {
   349  		return false
   350  	}
   351  	return true
   352  }
   353  
   354  func asn1Unsigned(out *uint64, n []byte) bool {
   355  	length := len(n)
   356  	if length > 9 || length == 9 && n[0] != 0 {
   357  		// Too large for uint64.
   358  		return false
   359  	}
   360  	if n[0]&0x80 != 0 {
   361  		// Negative number.
   362  		return false
   363  	}
   364  	for i := 0; i < length; i++ {
   365  		*out <<= 8
   366  		*out |= uint64(n[i])
   367  	}
   368  	return true
   369  }
   370  
   371  // ReadASN1Int64WithTag decodes an ASN.1 INTEGER with the given tag into out
   372  // and advances. It reports whether the read was successful and resulted in a
   373  // value that can be represented in an int64.
   374  func (s *String) ReadASN1Int64WithTag(out *int64, tag asn1.Tag) bool {
   375  	var bytes String
   376  	return s.ReadASN1(&bytes, tag) && checkASN1Integer(bytes) && asn1Signed(out, bytes)
   377  }
   378  
   379  // ReadASN1Enum decodes an ASN.1 ENUMERATION into out and advances. It reports
   380  // whether the read was successful.
   381  func (s *String) ReadASN1Enum(out *int) bool {
   382  	var bytes String
   383  	var i int64
   384  	if !s.ReadASN1(&bytes, asn1.ENUM) || !checkASN1Integer(bytes) || !asn1Signed(&i, bytes) {
   385  		return false
   386  	}
   387  	if int64(int(i)) != i {
   388  		return false
   389  	}
   390  	*out = int(i)
   391  	return true
   392  }
   393  
   394  func (s *String) readBase128Int(out *int) bool {
   395  	ret := 0
   396  	for i := 0; len(*s) > 0; i++ {
   397  		if i == 4 {
   398  			return false
   399  		}
   400  		ret <<= 7
   401  		b := s.read(1)[0]
   402  		ret |= int(b & 0x7f)
   403  		if b&0x80 == 0 {
   404  			*out = ret
   405  			return true
   406  		}
   407  	}
   408  	return false // truncated
   409  }
   410  
   411  // ReadASN1ObjectIdentifier decodes an ASN.1 OBJECT IDENTIFIER into out and
   412  // advances. It reports whether the read was successful.
   413  func (s *String) ReadASN1ObjectIdentifier(out *encoding_asn1.ObjectIdentifier) bool {
   414  	var bytes String
   415  	if !s.ReadASN1(&bytes, asn1.OBJECT_IDENTIFIER) || len(bytes) == 0 {
   416  		return false
   417  	}
   418  
   419  	// In the worst case, we get two elements from the first byte (which is
   420  	// encoded differently) and then every varint is a single byte long.
   421  	components := make([]int, len(bytes)+1)
   422  
   423  	// The first varint is 40*value1 + value2:
   424  	// According to this packing, value1 can take the values 0, 1 and 2 only.
   425  	// When value1 = 0 or value1 = 1, then value2 is <= 39. When value1 = 2,
   426  	// then there are no restrictions on value2.
   427  	var v int
   428  	if !bytes.readBase128Int(&v) {
   429  		return false
   430  	}
   431  	if v < 80 {
   432  		components[0] = v / 40
   433  		components[1] = v % 40
   434  	} else {
   435  		components[0] = 2
   436  		components[1] = v - 80
   437  	}
   438  
   439  	i := 2
   440  	for ; len(bytes) > 0; i++ {
   441  		if !bytes.readBase128Int(&v) {
   442  			return false
   443  		}
   444  		components[i] = v
   445  	}
   446  	*out = components[:i]
   447  	return true
   448  }
   449  
   450  // ReadASN1GeneralizedTime decodes an ASN.1 GENERALIZEDTIME into out and
   451  // advances. It reports whether the read was successful.
   452  func (s *String) ReadASN1GeneralizedTime(out *time.Time) bool {
   453  	var bytes String
   454  	if !s.ReadASN1(&bytes, asn1.GeneralizedTime) {
   455  		return false
   456  	}
   457  	t := string(bytes)
   458  	res, err := time.Parse(generalizedTimeFormatStr, t)
   459  	if err != nil {
   460  		return false
   461  	}
   462  	if serialized := res.Format(generalizedTimeFormatStr); serialized != t {
   463  		return false
   464  	}
   465  	*out = res
   466  	return true
   467  }
   468  
   469  // ReadASN1BitString decodes an ASN.1 BIT STRING into out and advances.
   470  // It reports whether the read was successful.
   471  func (s *String) ReadASN1BitString(out *encoding_asn1.BitString) bool {
   472  	var bytes String
   473  	if !s.ReadASN1(&bytes, asn1.BIT_STRING) || len(bytes) == 0 ||
   474  		len(bytes)*8/8 != len(bytes) {
   475  		return false
   476  	}
   477  
   478  	paddingBits := uint8(bytes[0])
   479  	bytes = bytes[1:]
   480  	if paddingBits > 7 ||
   481  		len(bytes) == 0 && paddingBits != 0 ||
   482  		len(bytes) > 0 && bytes[len(bytes)-1]&(1<<paddingBits-1) != 0 {
   483  		return false
   484  	}
   485  
   486  	out.BitLength = len(bytes)*8 - int(paddingBits)
   487  	out.Bytes = bytes
   488  	return true
   489  }
   490  
   491  // ReadASN1BitString decodes an ASN.1 BIT STRING into out and advances. It is
   492  // an error if the BIT STRING is not a whole number of bytes. It reports
   493  // whether the read was successful.
   494  func (s *String) ReadASN1BitStringAsBytes(out *[]byte) bool {
   495  	var bytes String
   496  	if !s.ReadASN1(&bytes, asn1.BIT_STRING) || len(bytes) == 0 {
   497  		return false
   498  	}
   499  
   500  	paddingBits := uint8(bytes[0])
   501  	if paddingBits != 0 {
   502  		return false
   503  	}
   504  	*out = bytes[1:]
   505  	return true
   506  }
   507  
   508  // ReadASN1Bytes reads the contents of a DER-encoded ASN.1 element (not including
   509  // tag and length bytes) into out, and advances. The element must match the
   510  // given tag. It reports whether the read was successful.
   511  func (s *String) ReadASN1Bytes(out *[]byte, tag asn1.Tag) bool {
   512  	return s.ReadASN1((*String)(out), tag)
   513  }
   514  
   515  // ReadASN1 reads the contents of a DER-encoded ASN.1 element (not including
   516  // tag and length bytes) into out, and advances. The element must match the
   517  // given tag. It reports whether the read was successful.
   518  //
   519  // Tags greater than 30 are not supported (i.e. low-tag-number format only).
   520  func (s *String) ReadASN1(out *String, tag asn1.Tag) bool {
   521  	var t asn1.Tag
   522  	if !s.ReadAnyASN1(out, &t) || t != tag {
   523  		return false
   524  	}
   525  	return true
   526  }
   527  
   528  // ReadASN1Element reads the contents of a DER-encoded ASN.1 element (including
   529  // tag and length bytes) into out, and advances. The element must match the
   530  // given tag. It reports whether the read was successful.
   531  //
   532  // Tags greater than 30 are not supported (i.e. low-tag-number format only).
   533  func (s *String) ReadASN1Element(out *String, tag asn1.Tag) bool {
   534  	var t asn1.Tag
   535  	if !s.ReadAnyASN1Element(out, &t) || t != tag {
   536  		return false
   537  	}
   538  	return true
   539  }
   540  
   541  // ReadAnyASN1 reads the contents of a DER-encoded ASN.1 element (not including
   542  // tag and length bytes) into out, sets outTag to its tag, and advances.
   543  // It reports whether the read was successful.
   544  //
   545  // Tags greater than 30 are not supported (i.e. low-tag-number format only).
   546  func (s *String) ReadAnyASN1(out *String, outTag *asn1.Tag) bool {
   547  	return s.readASN1(out, outTag, true /* skip header */)
   548  }
   549  
   550  // ReadAnyASN1Element reads the contents of a DER-encoded ASN.1 element
   551  // (including tag and length bytes) into out, sets outTag to is tag, and
   552  // advances. It reports whether the read was successful.
   553  //
   554  // Tags greater than 30 are not supported (i.e. low-tag-number format only).
   555  func (s *String) ReadAnyASN1Element(out *String, outTag *asn1.Tag) bool {
   556  	return s.readASN1(out, outTag, false /* include header */)
   557  }
   558  
   559  // PeekASN1Tag reports whether the next ASN.1 value on the string starts with
   560  // the given tag.
   561  func (s String) PeekASN1Tag(tag asn1.Tag) bool {
   562  	if len(s) == 0 {
   563  		return false
   564  	}
   565  	return asn1.Tag(s[0]) == tag
   566  }
   567  
   568  // SkipASN1 reads and discards an ASN.1 element with the given tag. It
   569  // reports whether the operation was successful.
   570  func (s *String) SkipASN1(tag asn1.Tag) bool {
   571  	var unused String
   572  	return s.ReadASN1(&unused, tag)
   573  }
   574  
   575  // ReadOptionalASN1 attempts to read the contents of a DER-encoded ASN.1
   576  // element (not including tag and length bytes) tagged with the given tag into
   577  // out. It stores whether an element with the tag was found in outPresent,
   578  // unless outPresent is nil. It reports whether the read was successful.
   579  func (s *String) ReadOptionalASN1(out *String, outPresent *bool, tag asn1.Tag) bool {
   580  	present := s.PeekASN1Tag(tag)
   581  	if outPresent != nil {
   582  		*outPresent = present
   583  	}
   584  	if present && !s.ReadASN1(out, tag) {
   585  		return false
   586  	}
   587  	return true
   588  }
   589  
   590  // SkipOptionalASN1 advances s over an ASN.1 element with the given tag, or
   591  // else leaves s unchanged. It reports whether the operation was successful.
   592  func (s *String) SkipOptionalASN1(tag asn1.Tag) bool {
   593  	if !s.PeekASN1Tag(tag) {
   594  		return true
   595  	}
   596  	var unused String
   597  	return s.ReadASN1(&unused, tag)
   598  }
   599  
   600  // ReadOptionalASN1Integer attempts to read an optional ASN.1 INTEGER
   601  // explicitly tagged with tag into out and advances. If no element with a
   602  // matching tag is present, it writes defaultValue into out instead. If out
   603  // does not point to an integer or to a big.Int, it panics. It reports
   604  // whether the read was successful.
   605  func (s *String) ReadOptionalASN1Integer(out interface{}, tag asn1.Tag, defaultValue interface{}) bool {
   606  	if reflect.TypeOf(out).Kind() != reflect.Ptr {
   607  		panic("out is not a pointer")
   608  	}
   609  	var present bool
   610  	var i String
   611  	if !s.ReadOptionalASN1(&i, &present, tag) {
   612  		return false
   613  	}
   614  	if !present {
   615  		switch reflect.ValueOf(out).Elem().Kind() {
   616  		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
   617  			reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
   618  			reflect.ValueOf(out).Elem().Set(reflect.ValueOf(defaultValue))
   619  		case reflect.Struct:
   620  			if reflect.TypeOf(out).Elem() != bigIntType {
   621  				panic("invalid integer type")
   622  			}
   623  			if reflect.TypeOf(defaultValue).Kind() != reflect.Ptr ||
   624  				reflect.TypeOf(defaultValue).Elem() != bigIntType {
   625  				panic("out points to big.Int, but defaultValue does not")
   626  			}
   627  			out.(*big.Int).Set(defaultValue.(*big.Int))
   628  		default:
   629  			panic("invalid integer type")
   630  		}
   631  		return true
   632  	}
   633  	if !i.ReadASN1Integer(out) || !i.Empty() {
   634  		return false
   635  	}
   636  	return true
   637  }
   638  
   639  // ReadOptionalASN1OctetString attempts to read an optional ASN.1 OCTET STRING
   640  // explicitly tagged with tag into out and advances. If no element with a
   641  // matching tag is present, it sets "out" to nil instead. It reports
   642  // whether the read was successful.
   643  func (s *String) ReadOptionalASN1OctetString(out *[]byte, outPresent *bool, tag asn1.Tag) bool {
   644  	var present bool
   645  	var child String
   646  	if !s.ReadOptionalASN1(&child, &present, tag) {
   647  		return false
   648  	}
   649  	if outPresent != nil {
   650  		*outPresent = present
   651  	}
   652  	if present {
   653  		var oct String
   654  		if !child.ReadASN1(&oct, asn1.OCTET_STRING) || !child.Empty() {
   655  			return false
   656  		}
   657  		*out = oct
   658  	} else {
   659  		*out = nil
   660  	}
   661  	return true
   662  }
   663  
   664  // ReadOptionalASN1Boolean sets *out to the value of the next ASN.1 BOOLEAN or,
   665  // if the next bytes are not an ASN.1 BOOLEAN, to the value of defaultValue.
   666  // It reports whether the operation was successful.
   667  func (s *String) ReadOptionalASN1Boolean(out *bool, defaultValue bool) bool {
   668  	var present bool
   669  	var child String
   670  	if !s.ReadOptionalASN1(&child, &present, asn1.BOOLEAN) {
   671  		return false
   672  	}
   673  
   674  	if !present {
   675  		*out = defaultValue
   676  		return true
   677  	}
   678  
   679  	return s.ReadASN1Boolean(out)
   680  }
   681  
   682  func (s *String) readASN1(out *String, outTag *asn1.Tag, skipHeader bool) bool {
   683  	if len(*s) < 2 {
   684  		return false
   685  	}
   686  	tag, lenByte := (*s)[0], (*s)[1]
   687  
   688  	if tag&0x1f == 0x1f {
   689  		// ITU-T X.690 section 8.1.2
   690  		//
   691  		// An identifier octet with a tag part of 0x1f indicates a high-tag-number
   692  		// form identifier with two or more octets. We only support tags less than
   693  		// 31 (i.e. low-tag-number form, single octet identifier).
   694  		return false
   695  	}
   696  
   697  	if outTag != nil {
   698  		*outTag = asn1.Tag(tag)
   699  	}
   700  
   701  	// ITU-T X.690 section 8.1.3
   702  	//
   703  	// Bit 8 of the first length byte indicates whether the length is short- or
   704  	// long-form.
   705  	var length, headerLen uint32 // length includes headerLen
   706  	if lenByte&0x80 == 0 {
   707  		// Short-form length (section 8.1.3.4), encoded in bits 1-7.
   708  		length = uint32(lenByte) + 2
   709  		headerLen = 2
   710  	} else {
   711  		// Long-form length (section 8.1.3.5). Bits 1-7 encode the number of octets
   712  		// used to encode the length.
   713  		lenLen := lenByte & 0x7f
   714  		var len32 uint32
   715  
   716  		if lenLen == 0 || lenLen > 4 || len(*s) < int(2+lenLen) {
   717  			return false
   718  		}
   719  
   720  		lenBytes := String((*s)[2 : 2+lenLen])
   721  		if !lenBytes.readUnsigned(&len32, int(lenLen)) {
   722  			return false
   723  		}
   724  
   725  		// ITU-T X.690 section 10.1 (DER length forms) requires encoding the length
   726  		// with the minimum number of octets.
   727  		if len32 < 128 {
   728  			// Length should have used short-form encoding.
   729  			return false
   730  		}
   731  		if len32>>((lenLen-1)*8) == 0 {
   732  			// Leading octet is 0. Length should have been at least one byte shorter.
   733  			return false
   734  		}
   735  
   736  		headerLen = 2 + uint32(lenLen)
   737  		if headerLen+len32 < len32 {
   738  			// Overflow.
   739  			return false
   740  		}
   741  		length = headerLen + len32
   742  	}
   743  
   744  	if int(length) < 0 || !s.ReadBytes((*[]byte)(out), int(length)) {
   745  		return false
   746  	}
   747  	if skipHeader && !out.Skip(int(headerLen)) {
   748  		panic("cryptobyte: internal error")
   749  	}
   750  
   751  	return true
   752  }
   753  
   754  const defaultUTCTimeFormatStr = "060102150405Z0700"
   755  
   756  // ReadASN1UTCTime decodes an ASN.1 UTCTime into out and advances.
   757  // It reports whether the read was successful.
   758  func (s *String) ReadASN1UTCTime(out *time.Time) bool {
   759  	var bytes String
   760  	if !s.ReadASN1(&bytes, asn1.UTCTime) {
   761  		return false
   762  	}
   763  	t := string(bytes)
   764  
   765  	formatStr := defaultUTCTimeFormatStr
   766  	var err error
   767  	res, err := time.Parse(formatStr, t)
   768  	if err != nil {
   769  		// Fallback to minute precision if we can't parse second
   770  		// precision. If we are following X.509 or X.690 we shouldn't
   771  		// support this, but we do.
   772  		formatStr = "0601021504Z0700"
   773  		res, err = time.Parse(formatStr, t)
   774  	}
   775  	if err != nil {
   776  		return false
   777  	}
   778  
   779  	if serialized := res.Format(formatStr); serialized != t {
   780  		return false
   781  	}
   782  
   783  	if res.Year() >= 2050 {
   784  		// UTCTime interprets the low order digits 50-99 as 1950-99.
   785  		// This only applies to its use in the X.509 profile.
   786  		// See https://tools.ietf.org/html/rfc5280#section-4.1.2.5.1
   787  		res = res.AddDate(-100, 0, 0)
   788  	}
   789  	*out = res
   790  	return true
   791  }