asn1

package
v1.0.2078 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 5, 2024 License: Apache-2.0 Imports: 12 Imported by: 0

README

ASN.1

 █████  ███████ ███    ██     ██ 
██   ██ ██      ████   ██    ███ 
███████ ███████ ██ ██  ██     ██ 
██   ██      ██ ██  ██ ██     ██ 
██   ██ ███████ ██   ████ ██  ██ 

BER encoder/decoder

Encoding and decoding of ASN.1 (Abstract Syntax Notation One) (X.208) abstract objects using BER (Basic Encoding Rules) (X.209).

Basic Encoding Rules

A BER encoding consists of 3 components:

  • Identifier octets
  • Length octets
  • Contents octets
Identifier octets

The identifier octets encode the ASN.1 tag (class and number) of the type of the data value.

Low Tags (0 - 30)

Single octet

  • Bits 8 + 7: class of the tag
  • Bit 6: 0 if primitive, 1 if constructed
  • Bit 5 - 1: tag number, encoded as a binary integer
High Tags (>= 31)

2+ octets

  • Bit 8 + 7: class of the tag
  • Bit 6: 0 if primitive, 1 if constructed
  • Bits 5 - 1: 11111
  • 2nd octet: tag number base-128 encoded
Length octets

Can be in definite and indefinite form. We don't use indefinite.

Definite form
  • 1 or more octets
  • Represents the number of octets in the contetns octets
  • Can be in short or long form
Short form

Contents octets <= 127

  • Single octet
  • Bit 8: 0
  • Bits 7 - 1: Number of content octets (may be zero), as an unsigned bianry integer

Example:

Number of content octets = 38

Short from length encoding: b00100110

Long form

Contents octets > 127

  • Initial octet + one or more subsequent octets
  • Initial octet
    • Bit 8: 1
    • Bit 7 - 1: Number of subsequent octets in length octets, as an unsigned binary integer
    • Value b11111111 cannot be used
  • Subsequent octets
    • Encoding of unsigned binary integer equal to the number of content octets

Example:

Number of content octets = 201

Long from length encoding: 0b10000001 0b11001001

Tag Class
Class Bit 8 Bit 7 Definition
Universal 0 0 Meaning is the same in all applications
Application 0 1 Meaning is specific to an application (i.e. LDAP)
Context-specific 1 0 Meaning is specific to a particular usage within a given application.
Private 1 1 Meaning is specific to a given enterprise
Base-128

For each octet:

  • Bit 8: 1, except last octet
  • Bit 7 - 1: encoding of the unsigned binary integer

Bits 7 - 1 of the first subsequent octet cannot be all zero.

Universal types
  • BIT STRING: an arbitrary string of bits.
  • IA5String: an arbitrary string of IA5 (ASCII) characters.
  • INTEGER: an arbitrary integer.
  • NULL: a null value.
  • OBJECT IDENTIFIER: an object identifier
  • OCTET STRING: an arbitrary string of octets.
  • PrintableString: an arbitrary string of printable characters.
  • T61String: an arbitrary string of T.61 characters.
  • UTCTime: a UTC timestamp
Structured types
  • SEQUENCE: ordered collection of items of one or more types
  • SEQUENCE OF: ordered collection of zero or more items of the same type
  • SET: unordered collection of items of one or more types
  • SET OF unordered collection of zero or more items of the same type
Implicity and explicity tagged types

Implicitly tagged types are derived from other types by changing the tag of the underlying type.

Explicitly tagged types are derived from other types by adding an outer tag to the underlying type. Effectively a structured type consisting of one component: the underlying type.

These can be translated as:

IMPLICIT: instead of

EXPLICIT: in addition to

EXPLICIT is the default.

Type Encodings
BIT STRING

Primitive or constructed.

Constructed not supported.

BIT STRING is an arbitrary string of bits. Can have any length, including zero.

The first contents octets give the number of unused bits. The second and following contents octets give the value of the bit string, converted to an octet string.

The bit string is padded after the last bit with zero to seven bits to make the length of the bit string a multiple of eight (so no padding if the length already is a multiple of eight).

Example: 011011100101110111 -> 01101110 01011101 11000000 (6e 5d c0) (6 unused bits)

Then in Go:

bitString, _ := NewBitString([]byte{0x6e, 0x5d, 0xc0}, 6)
IA5String

Primitive or constructed.

Constructed not supported.

IA5String is an arbitrary string of IA5 characters (ASCII).

INTEGER

Primitive

INTEGER is an arbitrary integer. Contents octets are the value of the integer, base-256, two's complement form, big-endian, with minimum number of octets.

ENUMERATED

Encoding is exactly the same as an INTEGER.

NULL

Primitive

NULL denotes a null value. Contents octets are empty.

OBJECT IDENTIFIER

Primitive

OBJECT IDENTIFIER denotes an object identifier.

The first octet has the value 40 * oid[0] + oid[1]. oid[0] is limited to 0, 1 and 2. oid[1] is limited to 0 to 39 when oid[0] is 0 or 1.

The following octets are each value encoded, base-128, big-endian, with minimum number of octets. The most significant bit of each octet, except the last, must be 1.

OCTET STRING

Primitive or constructed.

Constructed not supported.

OCTET STRING denotes an arbitrary string of octets.

The encoding is the value of the octet string.

PrintableString

Primitive or constructed.

Constructed not supported.

PrintableString is an arbitrary string of printable characters from the following set:

A, B, ..., Z
a, b, ..., z
0, 1, ..., 9
(space) ' ( ) + , - . / : = ?
SEQUENCE

Constructed

SEQUENCE denotes an ordered collection of one or more types.

Contents octets are the concatenation of the BER encodings of the values of the components of the sequence, in order of definition.

If a compnent has an OPTIONAL or DEFAULT qualifier, and is absent from the sequence during encoding, that component is not included in the contents octets. If the compnent with a DEFAULT qualifier is the default value during the encoding, it may or may not be included in the contents octets.

SEQUENCE OF

Constructed

SEQUENCE OF denotes an ordered collection of zero or more occurrences of a given type.

Contents octets are the concatenation of the BER encodings of the values of the components of the sequence, in order of definition.

SET

Constructed

SET denotes an unordered collection of one or more types.

Contents octets are the concatenation of the BER encodings of the values of the components of the set, in any order.

If a compnent has an OPTIONAL or DEFAULT qualifier, and is absent from the sequence during encoding, that component is not included in the contents octets. If the compnent with a DEFAULT qualifier is the default value during the encoding, it may or may not be included in the contents octets.

SET OF

Constructed

SET OF denotes an unordered collection of zero or more occurrences of a given type.

Contents octets are the concatenation of the BER encodings of the values of the components of the set, in any order.

T61String

Primitive or constructed.

Constructed not supported.

T61String is an arbitrary string of T.61 characters.

UTCTime

Primitive or constructed.

Constructed not supported.

UTCTime denotes a UTC timestamp. Can be in the following formats:

YYMMDDhhmmZ
YYMMDDhhmm+hh'mm'
YYMMDDhhmm-hh'mm'
YYMMDDhhmmssZ
YYMMDDhhmmss+hh'mm'
YYMMDDhhmmss-hh'mm'

It is encoded as an ASCII string.

Example:

May 6, 1991 4:45:40 PM PDT

Can be formatted as:

  • 910506164540-0700
  • 910506234540Z

References

ITU-T X.690 - BER spec

A Layman's Guide to a Subset of ASN.1, BER, and DER

Basic Encoding Rules - Sun OpenDS Standard Edition 2.2 Glossary of LDAP and Directory Terminology

LDAPv3 Wire Protocol Reference: The ASN.1 Basic Encoding Rules

X.690 - Wikipedia

A Warm Welcome to ASN.1 and DER

ASN.1 by simple words - Yury Strozhevsky

Books

ASN.1 Communication Between Heterogeneous Systems - Olivier Dubuisson

ASN.1 Complete - John Larmouth

Tools

ASN.1 JavaScript decoder

ASN.1 Playground

Documentation

Index

Constants

This section is empty.

Variables

View Source
var NullBytes = []byte{byte(TagNull), 0}

NullBytes contains bytes representing the BER-encoded ASN.1 NULL type.

View Source
var NullRawValue = RawValue{Tag: int(TagNull)}

NullRawValue is a RawValue with its Tag set to the ASN.1 NULL type tag (5).

Functions

func Marshal

func Marshal(v any) ([]byte, error)

func MarshalWithOptions

func MarshalWithOptions(v any, optionsString string) ([]byte, error)

func NewBoolEncoder added in v1.0.2017

func NewBoolEncoder(d bool) boolEncoder

func NewBoolEncoderWithInt added in v1.0.2017

func NewBoolEncoderWithInt(d int) boolEncoder

func Unmarshal

func Unmarshal(b []byte, val any) (rest []byte, err error)

Unmarshal parses the BER-encoded ASN.1 data structure b and uses the reflect package to fill in an arbitrary value pointed at by val. Because Unmarshal uses the reflect package, the structs being written to must use upper case field names.

An ASN.1 INTEGER can be written to an int, int32, int64, or *big.Int (from the math/big package). If the encoded value does not fit in the Go type, Unmarshal returns a parse error.

An ASN.1 BIT STRING can be written to a BitString.

An ASN.1 OCTET STRING can be written to a []byte.

An ASN.1 OBJECT IDENTIFIER can be written to an ObjectIdentifier.

An ASN.1 ENUMERATED can be written to an Enumerated.

An ASN.1 UTCTIME or GENERALIZEDTIME can be written to a time.Time.

An ASN.1 PrintableString, IA5String, or NumericString can be written to a string.

Any of the above ASN.1 values can be written to an any. The value stored in the interface has the corresponding Go type. For integers, that type is int64.

An ASN.1 SEQUENCE OF x or SET OF x can be written to a slice if an x can be written to the slice's element type.

An ASN.1 SEQUENCE or SET can be written to a struct if each of the elements in the sequence can be written to the corresponding element in the struct.

The following tags on struct fields have special meaning to Unmarshal:

application specifies that an APPLICATION tag is used
private     specifies that a PRIVATE tag is used
default:x   sets the default value for optional integer fields (only used if optional is also present)
explicit    specifies that an additional, explicit tag wraps the implicit one
optional    marks the field as ASN.1 OPTIONAL
set         causes a SET, rather than a SEQUENCE type to be expected
tag:x       specifies the ASN.1 tag number; implies ASN.1 CONTEXT SPECIFIC

If the type of the first field of a structure is RawContent then the raw ASN1 contents of the struct will be stored in it.

If the type name of a slice element ends with "SET" then it's treated as if the "set" tag was set on it. This can be used with nested slices where a struct tag cannot be given.

Other ASN.1 types are not supported; if it encounters them, Unmarshal returns a parse error.

func UnmarshalWithParams

func UnmarshalWithParams(b []byte, val any, params string) (rest []byte, err error)

UnmarshalWithParams allows field parameters to be specified for the top-level element. The form of the params is the same as the field tags.

Types

type BitString

type BitString struct {
	Bytes     []byte // bits packed into bytes.
	BitLength int    // length in bits.
}

func (BitString) At added in v1.0.2017

func (b BitString) At(i int) int

At returns the bit at the given index. If the index is out of range it returns 0.

func (BitString) RightAlign added in v1.0.2017

func (b BitString) RightAlign() []byte

RightAlign returns a slice where the padding bits are at the beginning. The slice may share memory with the BitString.

type Encoder

type Encoder struct {
	// contains filtered or unexported fields
}

func NewEncoder

func NewEncoder(v any, opts *options) Encoder

type Enumerated

type Enumerated int

An Enumerated is represented as a plain int.

type Flag

type Flag bool

A Flag accepts any data and is set to true if present.

type Null

type Null struct{}

type ObjectIdentifier

type ObjectIdentifier []int

func NewObjectIdentifier

func NewObjectIdentifier(root int, node []int) (ObjectIdentifier, error)

func (ObjectIdentifier) Equal

func (oi ObjectIdentifier) Equal(other ObjectIdentifier) bool

Equal reports whether oi and other represent the same identifier.

func (ObjectIdentifier) String

func (oi ObjectIdentifier) String() string

type RawContent

type RawContent []byte

RawContent is used to signal that the undecoded, DER data needs to be preserved for a struct. To use it, the first field of the struct must have this type. It's an error for any of the other fields to have this type.

type RawValue added in v1.0.2017

type RawValue struct {
	Class, Tag   int
	IsCompound   bool
	IsIndefinite bool
	Bytes        []byte
	FullBytes    []byte // includes the tag and length
}

A RawValue represents an undecoded ASN.1 object.

type StructuralError

type StructuralError struct {
	Msg string
}

A StructuralError suggests that the ASN.1 data is valid, but the Go type which is receiving it doesn't match.

func (StructuralError) Error

func (e StructuralError) Error() string

type SyntaxError

type SyntaxError struct {
	Msg string
}

A SyntaxError suggests that the ASN.1 data is invalid.

func (SyntaxError) Error

func (e SyntaxError) Error() string

type Tag

type Tag uint
const (
	TagBoolean          Tag = 0x01
	TagInteger          Tag = 0x02
	TagBitString        Tag = 0x03
	TagOctetString      Tag = 0x04
	TagNull             Tag = 0x05
	TagObjectIdentifier Tag = 0x06
	TagObjectDescriptor Tag = 0x07
	TagExternal         Tag = 0x08
	TagReal             Tag = 0x09
	TagEnumerated       Tag = 0x0a
	TagEmbeddedPdv      Tag = 0x0b
	TagUtf8String       Tag = 0x0c
	TagRelativeOid      Tag = 0x0d
	TagTime             Tag = 0x0e
	TagSequence         Tag = 0x10
	TagSequenceOf       Tag = 0x10
	TagSet              Tag = 0x11
	TagSetOf            Tag = 0x11
	TagNumericString    Tag = 0x12
	TagPrintableString  Tag = 0x13
	TagT61String        Tag = 0x14
	TagVideotexString   Tag = 0x15
	TagIa5String        Tag = 0x16
	TagUtcTime          Tag = 0x17
	TagGeneralizedTime  Tag = 0x18
	TagGraphicString    Tag = 0x19
	TagVisibleString    Tag = 0x1a
	TagGeneralString    Tag = 0x1b
	TagUniversalString  Tag = 0x1c
	TagCharacterString  Tag = 0x1d
	TagBmpString        Tag = 0x1e
	TagDate             Tag = 0x1f
	TagTimeOfDay        Tag = 0x20
	TagDateTime         Tag = 0x21
	TagDuration         Tag = 0x22
	TagOidIri           Tag = 0x23
	TagRelativeOidIri   Tag = 0x24
)

type TagClass

type TagClass uint8
const (
	TagClassUniversal       TagClass = 0x00
	TagClassApplication     TagClass = 0x01
	TagClassContextSpecific TagClass = 0x02
	TagClassPrivate         TagClass = 0x03
)

type UnsupportedTypeError

type UnsupportedTypeError struct {
	Type reflect.Type
}

func (*UnsupportedTypeError) Error

func (e *UnsupportedTypeError) Error() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL