github.com/icodeface/tls@v0.0.0-20230910023335-34df9250cd12/internal/x/crypto/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  	encoding_asn1 "encoding/asn1"
     9  	"fmt"
    10  	"math/big"
    11  	"reflect"
    12  	"time"
    13  
    14  	"github.com/icodeface/tls/internal/x/crypto/cryptobyte/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 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 INTEGER 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.INTEGER) || 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  		return false
   475  	}
   476  
   477  	paddingBits := uint8(bytes[0])
   478  	bytes = bytes[1:]
   479  	if paddingBits > 7 ||
   480  		len(bytes) == 0 && paddingBits != 0 ||
   481  		len(bytes) > 0 && bytes[len(bytes)-1]&(1<<paddingBits-1) != 0 {
   482  		return false
   483  	}
   484  
   485  	out.BitLength = len(bytes)*8 - int(paddingBits)
   486  	out.Bytes = bytes
   487  	return true
   488  }
   489  
   490  // ReadASN1BitString decodes an ASN.1 BIT STRING into out and advances. It is
   491  // an error if the BIT STRING is not a whole number of bytes. It reports
   492  // whether the read was successful.
   493  func (s *String) ReadASN1BitStringAsBytes(out *[]byte) bool {
   494  	var bytes String
   495  	if !s.ReadASN1(&bytes, asn1.BIT_STRING) || len(bytes) == 0 {
   496  		return false
   497  	}
   498  
   499  	paddingBits := uint8(bytes[0])
   500  	if paddingBits != 0 {
   501  		return false
   502  	}
   503  	*out = bytes[1:]
   504  	return true
   505  }
   506  
   507  // ReadASN1Bytes reads the contents of a DER-encoded ASN.1 element (not including
   508  // tag and length bytes) into out, and advances. The element must match the
   509  // given tag. It reports whether the read was successful.
   510  func (s *String) ReadASN1Bytes(out *[]byte, tag asn1.Tag) bool {
   511  	return s.ReadASN1((*String)(out), tag)
   512  }
   513  
   514  // ReadASN1 reads the contents of a DER-encoded ASN.1 element (not including
   515  // tag and length bytes) into out, and advances. The element must match the
   516  // given tag. It reports whether the read was successful.
   517  //
   518  // Tags greater than 30 are not supported (i.e. low-tag-number format only).
   519  func (s *String) ReadASN1(out *String, tag asn1.Tag) bool {
   520  	var t asn1.Tag
   521  	if !s.ReadAnyASN1(out, &t) || t != tag {
   522  		return false
   523  	}
   524  	return true
   525  }
   526  
   527  // ReadASN1Element reads the contents of a DER-encoded ASN.1 element (including
   528  // tag and length bytes) into out, and advances. The element must match the
   529  // given tag. It reports whether the read was successful.
   530  //
   531  // Tags greater than 30 are not supported (i.e. low-tag-number format only).
   532  func (s *String) ReadASN1Element(out *String, tag asn1.Tag) bool {
   533  	var t asn1.Tag
   534  	if !s.ReadAnyASN1Element(out, &t) || t != tag {
   535  		return false
   536  	}
   537  	return true
   538  }
   539  
   540  // ReadAnyASN1 reads the contents of a DER-encoded ASN.1 element (not including
   541  // tag and length bytes) into out, sets outTag to its tag, and advances.
   542  // It reports whether the read was successful.
   543  //
   544  // Tags greater than 30 are not supported (i.e. low-tag-number format only).
   545  func (s *String) ReadAnyASN1(out *String, outTag *asn1.Tag) bool {
   546  	return s.readASN1(out, outTag, true /* skip header */)
   547  }
   548  
   549  // ReadAnyASN1Element reads the contents of a DER-encoded ASN.1 element
   550  // (including tag and length bytes) into out, sets outTag to is tag, and
   551  // advances. It reports whether the read was successful.
   552  //
   553  // Tags greater than 30 are not supported (i.e. low-tag-number format only).
   554  func (s *String) ReadAnyASN1Element(out *String, outTag *asn1.Tag) bool {
   555  	return s.readASN1(out, outTag, false /* include header */)
   556  }
   557  
   558  // PeekASN1Tag reports whether the next ASN.1 value on the string starts with
   559  // the given tag.
   560  func (s String) PeekASN1Tag(tag asn1.Tag) bool {
   561  	if len(s) == 0 {
   562  		return false
   563  	}
   564  	return asn1.Tag(s[0]) == tag
   565  }
   566  
   567  // SkipASN1 reads and discards an ASN.1 element with the given tag. It
   568  // reports whether the operation was successful.
   569  func (s *String) SkipASN1(tag asn1.Tag) bool {
   570  	var unused String
   571  	return s.ReadASN1(&unused, tag)
   572  }
   573  
   574  // ReadOptionalASN1 attempts to read the contents of a DER-encoded ASN.1
   575  // element (not including tag and length bytes) tagged with the given tag into
   576  // out. It stores whether an element with the tag was found in outPresent,
   577  // unless outPresent is nil. It reports whether the read was successful.
   578  func (s *String) ReadOptionalASN1(out *String, outPresent *bool, tag asn1.Tag) bool {
   579  	present := s.PeekASN1Tag(tag)
   580  	if outPresent != nil {
   581  		*outPresent = present
   582  	}
   583  	if present && !s.ReadASN1(out, tag) {
   584  		return false
   585  	}
   586  	return true
   587  }
   588  
   589  // SkipOptionalASN1 advances s over an ASN.1 element with the given tag, or
   590  // else leaves s unchanged. It reports whether the operation was successful.
   591  func (s *String) SkipOptionalASN1(tag asn1.Tag) bool {
   592  	if !s.PeekASN1Tag(tag) {
   593  		return true
   594  	}
   595  	var unused String
   596  	return s.ReadASN1(&unused, tag)
   597  }
   598  
   599  // ReadOptionalASN1Integer attempts to read an optional ASN.1 INTEGER
   600  // explicitly tagged with tag into out and advances. If no element with a
   601  // matching tag is present, it writes defaultValue into out instead. If out
   602  // does not point to an integer or to a big.Int, it panics. It reports
   603  // whether the read was successful.
   604  func (s *String) ReadOptionalASN1Integer(out interface{}, tag asn1.Tag, defaultValue interface{}) bool {
   605  	if reflect.TypeOf(out).Kind() != reflect.Ptr {
   606  		panic("out is not a pointer")
   607  	}
   608  	var present bool
   609  	var i String
   610  	if !s.ReadOptionalASN1(&i, &present, tag) {
   611  		return false
   612  	}
   613  	if !present {
   614  		switch reflect.ValueOf(out).Elem().Kind() {
   615  		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
   616  			reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
   617  			reflect.ValueOf(out).Elem().Set(reflect.ValueOf(defaultValue))
   618  		case reflect.Struct:
   619  			if reflect.TypeOf(out).Elem() != bigIntType {
   620  				panic("invalid integer type")
   621  			}
   622  			if reflect.TypeOf(defaultValue).Kind() != reflect.Ptr ||
   623  				reflect.TypeOf(defaultValue).Elem() != bigIntType {
   624  				panic("out points to big.Int, but defaultValue does not")
   625  			}
   626  			out.(*big.Int).Set(defaultValue.(*big.Int))
   627  		default:
   628  			panic("invalid integer type")
   629  		}
   630  		return true
   631  	}
   632  	if !i.ReadASN1Integer(out) || !i.Empty() {
   633  		return false
   634  	}
   635  	return true
   636  }
   637  
   638  // ReadOptionalASN1OctetString attempts to read an optional ASN.1 OCTET STRING
   639  // explicitly tagged with tag into out and advances. If no element with a
   640  // matching tag is present, it sets "out" to nil instead. It reports
   641  // whether the read was successful.
   642  func (s *String) ReadOptionalASN1OctetString(out *[]byte, outPresent *bool, tag asn1.Tag) bool {
   643  	var present bool
   644  	var child String
   645  	if !s.ReadOptionalASN1(&child, &present, tag) {
   646  		return false
   647  	}
   648  	if outPresent != nil {
   649  		*outPresent = present
   650  	}
   651  	if present {
   652  		var oct String
   653  		if !child.ReadASN1(&oct, asn1.OCTET_STRING) || !child.Empty() {
   654  			return false
   655  		}
   656  		*out = oct
   657  	} else {
   658  		*out = nil
   659  	}
   660  	return true
   661  }
   662  
   663  // ReadOptionalASN1Boolean sets *out to the value of the next ASN.1 BOOLEAN or,
   664  // if the next bytes are not an ASN.1 BOOLEAN, to the value of defaultValue.
   665  // It reports whether the operation was successful.
   666  func (s *String) ReadOptionalASN1Boolean(out *bool, defaultValue bool) bool {
   667  	var present bool
   668  	var child String
   669  	if !s.ReadOptionalASN1(&child, &present, asn1.BOOLEAN) {
   670  		return false
   671  	}
   672  
   673  	if !present {
   674  		*out = defaultValue
   675  		return true
   676  	}
   677  
   678  	return s.ReadASN1Boolean(out)
   679  }
   680  
   681  func (s *String) readASN1(out *String, outTag *asn1.Tag, skipHeader bool) bool {
   682  	if len(*s) < 2 {
   683  		return false
   684  	}
   685  	tag, lenByte := (*s)[0], (*s)[1]
   686  
   687  	if tag&0x1f == 0x1f {
   688  		// ITU-T X.690 section 8.1.2
   689  		//
   690  		// An identifier octet with a tag part of 0x1f indicates a high-tag-number
   691  		// form identifier with two or more octets. We only support tags less than
   692  		// 31 (i.e. low-tag-number form, single octet identifier).
   693  		return false
   694  	}
   695  
   696  	if outTag != nil {
   697  		*outTag = asn1.Tag(tag)
   698  	}
   699  
   700  	// ITU-T X.690 section 8.1.3
   701  	//
   702  	// Bit 8 of the first length byte indicates whether the length is short- or
   703  	// long-form.
   704  	var length, headerLen uint32 // length includes headerLen
   705  	if lenByte&0x80 == 0 {
   706  		// Short-form length (section 8.1.3.4), encoded in bits 1-7.
   707  		length = uint32(lenByte) + 2
   708  		headerLen = 2
   709  	} else {
   710  		// Long-form length (section 8.1.3.5). Bits 1-7 encode the number of octets
   711  		// used to encode the length.
   712  		lenLen := lenByte & 0x7f
   713  		var len32 uint32
   714  
   715  		if lenLen == 0 || lenLen > 4 || len(*s) < int(2+lenLen) {
   716  			return false
   717  		}
   718  
   719  		lenBytes := String((*s)[2 : 2+lenLen])
   720  		if !lenBytes.readUnsigned(&len32, int(lenLen)) {
   721  			return false
   722  		}
   723  
   724  		// ITU-T X.690 section 10.1 (DER length forms) requires encoding the length
   725  		// with the minimum number of octets.
   726  		if len32 < 128 {
   727  			// Length should have used short-form encoding.
   728  			return false
   729  		}
   730  		if len32>>((lenLen-1)*8) == 0 {
   731  			// Leading octet is 0. Length should have been at least one byte shorter.
   732  			return false
   733  		}
   734  
   735  		headerLen = 2 + uint32(lenLen)
   736  		if headerLen+len32 < len32 {
   737  			// Overflow.
   738  			return false
   739  		}
   740  		length = headerLen + len32
   741  	}
   742  
   743  	if uint32(int(length)) != length || !s.ReadBytes((*[]byte)(out), int(length)) {
   744  		return false
   745  	}
   746  	if skipHeader && !out.Skip(int(headerLen)) {
   747  		panic("cryptobyte: internal error")
   748  	}
   749  
   750  	return true
   751  }