asn1.mx raw

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