government / internal / der / der.go

@ ce159ec40272fb3caed2436702b1426f1550e47d | history


// Package der writes the few ASN.1 DER shapes GOVERNMENT needs for the
// certificate extensions Go cannot produce itself.
//
// Every DER value is a TLV: a tag byte saying what it is, the length of its
// content, and the content. DER is the one encoding of ASN.1 that allows
// exactly one byte string per value, which is what makes a signature over
// those bytes meaningful: a verifier re-encoding the same value gets the
// same bytes.
package der

import (
	"crypto/x509"
	"errors"
)

// Tags used here. Bit 0x20 marks a constructed value, one whose content is
// itself a series of TLVs.
const (
	TagOID        = 0x06
	TagUTF8String = 0x0c
	TagSequence   = 0x30
)

// TLV encodes one value. Lengths below 128 take one byte. Longer ones take
// 0x80 plus a count of length bytes, then the length in big-endian with no
// leading zeros; DER forbids every other way of writing a length.
func TLV(tag byte, content []byte) []byte {
	b := []byte{tag}
	n := len(content)
	if n < 0x80 {
		b = append(b, byte(n))
	} else {
		var digits []byte
		for ; n > 0; n >>= 8 {
			digits = append([]byte{byte(n)}, digits...)
		}
		b = append(b, 0x80|byte(len(digits)))
		b = append(b, digits...)
	}
	return append(b, content...)
}

func Sequence(elements ...[]byte) []byte {
	var content []byte
	for _, e := range elements {
		content = append(content, e...)
	}
	return TLV(TagSequence, content)
}

func UTF8String(s string) []byte {
	return TLV(TagUTF8String, []byte(s))
}

// OID encodes oid. x509.OID already holds the content bytes, which is the
// only way to carry an arc wider than 64 bits such as the GOV root's.
func OID(oid x509.OID) []byte {
	content, err := oid.MarshalBinary()
	if err != nil {
		// MarshalBinary only reports an OID that was never set.
		panic(err)
	}
	return TLV(TagOID, content)
}

// OIDContent encodes arcs as an OID's content bytes. The first two arcs
// share one value, 40*first + second, which is why the first arc is
// limited to 0, 1 or 2.
func OIDContent(arcs ...uint64) ([]byte, error) {
	if len(arcs) < 2 {
		return nil, errors.New("an OID needs at least two arcs")
	}
	if arcs[0] > 2 || (arcs[0] < 2 && arcs[1] >= 40) {
		return nil, errors.New("invalid first two arcs")
	}
	if arcs[0] == 2 && arcs[1] > (1<<64-1)-80 {
		return nil, errors.New("second arc too large")
	}
	b := AppendArc(nil, arcs[0]*40+arcs[1])
	for _, arc := range arcs[2:] {
		b = AppendArc(b, arc)
	}
	return b, nil
}

// AppendArc writes one arc in base 128, high digits first, with the top bit
// set on every byte but the last. That top bit is how a reader finds where
// each arc ends.
func AppendArc(b []byte, arc uint64) []byte {
	var digits [10]byte
	i := len(digits)
	for {
		i--
		digits[i] = byte(arc & 0x7f)
		arc >>= 7
		if arc == 0 {
			break
		}
	}
	for j := i; j < len(digits)-1; j++ {
		digits[j] |= 0x80
	}
	return append(b, digits[i:]...)
}