// Copyright 2017 The Go Authors. All rights reserved.// Use of this source code is governed by a BSD-style// license that can be found in the LICENSE file.package cryptobyteimport (encoding_asn1)// This file contains ASN.1-related methods for String and Builder.// Builder// AddASN1Int64 appends a DER-encoded ASN.1 INTEGER.func ( *Builder) ( int64) { .addASN1Signed(asn1.INTEGER, )}// AddASN1Int64WithTag appends a DER-encoded ASN.1 INTEGER with the// given tag.func ( *Builder) ( int64, asn1.Tag) { .addASN1Signed(, )}// AddASN1Enum appends a DER-encoded ASN.1 ENUMERATION.func ( *Builder) ( int64) { .addASN1Signed(asn1.ENUM, )}func ( *Builder) ( asn1.Tag, int64) { .AddASN1(, func( *Builder) { := 1for := ; >= 0x80 || < -0x80; >>= 8 { ++ }for ; > 0; -- { := >> uint((-1)*8) & 0xff .AddUint8(uint8()) } })}// AddASN1Uint64 appends a DER-encoded ASN.1 INTEGER.func ( *Builder) ( uint64) { .AddASN1(asn1.INTEGER, func( *Builder) { := 1for := ; >= 0x80; >>= 8 { ++ }for ; > 0; -- { := >> uint((-1)*8) & 0xff .AddUint8(uint8()) } })}// AddASN1BigInt appends a DER-encoded ASN.1 INTEGER.func ( *Builder) ( *big.Int) {if .err != nil {return } .AddASN1(asn1.INTEGER, func( *Builder) {if .Sign() < 0 {// A negative number has to be converted to two's-complement form. So we // invert and subtract 1. If the most-significant-bit isn't set then // we'll need to pad the beginning with 0xff in order to keep the number // negative. := new(big.Int).Neg() .Sub(, bigOne) := .Bytes()for := range { [] ^= 0xff }iflen() == 0 || [0]&0x80 == 0 { .add(0xff) } .add(...) } elseif .Sign() == 0 { .add(0) } else { := .Bytes()if [0]&0x80 != 0 { .add(0) } .add(...) } })}// AddASN1OctetString appends a DER-encoded ASN.1 OCTET STRING.func ( *Builder) ( []byte) { .AddASN1(asn1.OCTET_STRING, func( *Builder) { .AddBytes() })}const generalizedTimeFormatStr = "20060102150405Z0700"// AddASN1GeneralizedTime appends a DER-encoded ASN.1 GENERALIZEDTIME.func ( *Builder) ( time.Time) {if .Year() < 0 || .Year() > 9999 { .err = fmt.Errorf("cryptobyte: cannot represent %v as a GeneralizedTime", )return } .AddASN1(asn1.GeneralizedTime, func( *Builder) { .AddBytes([]byte(.Format(generalizedTimeFormatStr))) })}// AddASN1UTCTime appends a DER-encoded ASN.1 UTCTime.func ( *Builder) ( time.Time) { .AddASN1(asn1.UTCTime, func( *Builder) {// As utilized by the X.509 profile, UTCTime can only // represent the years 1950 through 2049.if .Year() < 1950 || .Year() >= 2050 { .err = fmt.Errorf("cryptobyte: cannot represent %v as a UTCTime", )return } .AddBytes([]byte(.Format(defaultUTCTimeFormatStr))) })}// AddASN1BitString appends a DER-encoded ASN.1 BIT STRING. This does not// support BIT STRINGs that are not a whole number of bytes.func ( *Builder) ( []byte) { .AddASN1(asn1.BIT_STRING, func( *Builder) { .AddUint8(0) .AddBytes() })}func ( *Builder) ( int64) {varintif == 0 { = 1 } else {for := ; > 0; >>= 7 { ++ } }for := - 1; >= 0; -- { := byte( >> uint(*7)) &= 0x7fif != 0 { |= 0x80 } .add() }}func isValidOID( encoding_asn1.ObjectIdentifier) bool {iflen() < 2 {returnfalse }if [0] > 2 || ([0] <= 1 && [1] >= 40) {returnfalse }for , := range {if < 0 {returnfalse } }returntrue}func ( *Builder) ( encoding_asn1.ObjectIdentifier) { .AddASN1(asn1.OBJECT_IDENTIFIER, func( *Builder) {if !isValidOID() { .err = fmt.Errorf("cryptobyte: invalid OID: %v", )return } .addBase128Int(int64([0])*40 + int64([1]))for , := range [2:] { .addBase128Int(int64()) } })}func ( *Builder) ( bool) { .AddASN1(asn1.BOOLEAN, func( *Builder) {if { .AddUint8(0xff) } else { .AddUint8(0) } })}func ( *Builder) () { .add(uint8(asn1.NULL), 0)}// MarshalASN1 calls encoding_asn1.Marshal on its input and appends the result if// successful or records an error if one occurred.func ( *Builder) ( interface{}) {// NOTE(martinkr): This is somewhat of a hack to allow propagation of // encoding_asn1.Marshal errors into Builder.err. N.B. if you call MarshalASN1 with a // value embedded into a struct, its tag information is lost.if .err != nil {return } , := encoding_asn1.Marshal()if != nil { .err = return } .AddBytes()}// AddASN1 appends an ASN.1 object. The object is prefixed with the given tag.// Tags greater than 30 are not supported and result in an error (i.e.// low-tag-number form only). The child builder passed to the// BuilderContinuation can be used to build the content of the ASN.1 object.func ( *Builder) ( asn1.Tag, BuilderContinuation) {if .err != nil {return }// Identifiers with the low five bits set indicate high-tag-number format // (two or more octets), which we don't support.if &0x1f == 0x1f { .err = fmt.Errorf("cryptobyte: high-tag number identifier octects not supported: 0x%x", )return } .AddUint8(uint8()) .addLengthPrefixed(1, true, )}// String// ReadASN1Boolean decodes an ASN.1 BOOLEAN and converts it to a boolean// representation into out and advances. It reports whether the read// was successful.func ( *String) ( *bool) bool {varStringif !.ReadASN1(&, asn1.BOOLEAN) || len() != 1 {returnfalse }switch [0] {case0: * = falsecase0xff: * = truedefault:returnfalse }returntrue}// ReadASN1Integer decodes an ASN.1 INTEGER into out and advances. If out does// not point to an integer, to a big.Int, or to a []byte it panics. Only// positive and zero values can be decoded into []byte, and they are returned as// big-endian binary values that share memory with s. Positive values will have// no leading zeroes, and zero will be returned as a single zero byte.// ReadASN1Integer reports whether the read was successful.func ( *String) ( interface{}) bool {switch out := .(type) {case *int, *int8, *int16, *int32, *int64:varint64if !.readASN1Int64(&) || reflect.ValueOf().Elem().OverflowInt() {returnfalse }reflect.ValueOf().Elem().SetInt()returntruecase *uint, *uint8, *uint16, *uint32, *uint64:varuint64if !.readASN1Uint64(&) || reflect.ValueOf().Elem().OverflowUint() {returnfalse }reflect.ValueOf().Elem().SetUint()returntruecase *big.Int:return .readASN1BigInt()case *[]byte:return .readASN1Bytes()default:panic("out does not point to an integer type") }}func checkASN1Integer( []byte) bool {iflen() == 0 {// An INTEGER is encoded with at least one octet.returnfalse }iflen() == 1 {returntrue }if [0] == 0 && [1]&0x80 == 0 || [0] == 0xff && [1]&0x80 == 0x80 {// Value is not minimally encoded.returnfalse }returntrue}var bigOne = big.NewInt(1)func ( *String) ( *big.Int) bool {varStringif !.ReadASN1(&, asn1.INTEGER) || !checkASN1Integer() {returnfalse }if [0]&0x80 == 0x80 {// Negative number. := make([]byte, len())for , := range { [] = ^ } .SetBytes() .Add(, bigOne) .Neg() } else { .SetBytes() }returntrue}func ( *String) ( *[]byte) bool {varStringif !.ReadASN1(&, asn1.INTEGER) || !checkASN1Integer() {returnfalse }if [0]&0x80 == 0x80 {returnfalse }forlen() > 1 && [0] == 0 { = [1:] } * = returntrue}func ( *String) ( *int64) bool {varStringif !.ReadASN1(&, asn1.INTEGER) || !checkASN1Integer() || !asn1Signed(, ) {returnfalse }returntrue}func asn1Signed( *int64, []byte) bool { := len()if > 8 {returnfalse }for := 0; < ; ++ { * <<= 8 * |= int64([]) }// Shift up and down in order to sign extend the result. * <<= 64 - uint8()*8 * >>= 64 - uint8()*8returntrue}func ( *String) ( *uint64) bool {varStringif !.ReadASN1(&, asn1.INTEGER) || !checkASN1Integer() || !asn1Unsigned(, ) {returnfalse }returntrue}func asn1Unsigned( *uint64, []byte) bool { := len()if > 9 || == 9 && [0] != 0 {// Too large for uint64.returnfalse }if [0]&0x80 != 0 {// Negative number.returnfalse }for := 0; < ; ++ { * <<= 8 * |= uint64([]) }returntrue}// ReadASN1Int64WithTag decodes an ASN.1 INTEGER with the given tag into out// and advances. It reports whether the read was successful and resulted in a// value that can be represented in an int64.func ( *String) ( *int64, asn1.Tag) bool {varStringreturn .ReadASN1(&, ) && checkASN1Integer() && asn1Signed(, )}// ReadASN1Enum decodes an ASN.1 ENUMERATION into out and advances. It reports// whether the read was successful.func ( *String) ( *int) bool {varStringvarint64if !.ReadASN1(&, asn1.ENUM) || !checkASN1Integer() || !asn1Signed(&, ) {returnfalse }ifint64(int()) != {returnfalse } * = int()returntrue}func ( *String) ( *int) bool { := 0for := 0; len(*) > 0; ++ {if == 5 {returnfalse }// Avoid overflowing int on a 32-bit platform. // We don't want different behavior based on the architecture.if >= 1<<(31-7) {returnfalse } <<= 7 := .read(1)[0]// ITU-T X.690, section 8.19.2: // The subidentifier shall be encoded in the fewest possible octets, // that is, the leading octet of the subidentifier shall not have the value 0x80.if == 0 && == 0x80 {returnfalse } |= int( & 0x7f)if &0x80 == 0 { * = returntrue } }returnfalse// truncated}// ReadASN1ObjectIdentifier decodes an ASN.1 OBJECT IDENTIFIER into out and// advances. It reports whether the read was successful.func ( *String) ( *encoding_asn1.ObjectIdentifier) bool {varStringif !.ReadASN1(&, asn1.OBJECT_IDENTIFIER) || len() == 0 {returnfalse }// In the worst case, we get two elements from the first byte (which is // encoded differently) and then every varint is a single byte long. := make([]int, len()+1)// The first varint is 40*value1 + value2: // According to this packing, value1 can take the values 0, 1 and 2 only. // When value1 = 0 or value1 = 1, then value2 is <= 39. When value1 = 2, // then there are no restrictions on value2.varintif !.readBase128Int(&) {returnfalse }if < 80 { [0] = / 40 [1] = % 40 } else { [0] = 2 [1] = - 80 } := 2for ; len() > 0; ++ {if !.readBase128Int(&) {returnfalse } [] = } * = [:]returntrue}// ReadASN1GeneralizedTime decodes an ASN.1 GENERALIZEDTIME into out and// advances. It reports whether the read was successful.func ( *String) ( *time.Time) bool {varStringif !.ReadASN1(&, asn1.GeneralizedTime) {returnfalse } := string() , := time.Parse(generalizedTimeFormatStr, )if != nil {returnfalse }if := .Format(generalizedTimeFormatStr); != {returnfalse } * = returntrue}const defaultUTCTimeFormatStr = "060102150405Z0700"// ReadASN1UTCTime decodes an ASN.1 UTCTime into out and advances.// It reports whether the read was successful.func ( *String) ( *time.Time) bool {varStringif !.ReadASN1(&, asn1.UTCTime) {returnfalse } := string() := defaultUTCTimeFormatStrvarerror , := time.Parse(, )if != nil {// Fallback to minute precision if we can't parse second // precision. If we are following X.509 or X.690 we shouldn't // support this, but we do. = "0601021504Z0700" , = time.Parse(, ) }if != nil {returnfalse }if := .Format(); != {returnfalse }if .Year() >= 2050 {// UTCTime interprets the low order digits 50-99 as 1950-99. // This only applies to its use in the X.509 profile. // See https://tools.ietf.org/html/rfc5280#section-4.1.2.5.1 = .AddDate(-100, 0, 0) } * = returntrue}// ReadASN1BitString decodes an ASN.1 BIT STRING into out and advances.// It reports whether the read was successful.func ( *String) ( *encoding_asn1.BitString) bool {varStringif !.ReadASN1(&, asn1.BIT_STRING) || len() == 0 ||len()*8/8 != len() {returnfalse } := [0] = [1:]if > 7 ||len() == 0 && != 0 ||len() > 0 && [len()-1]&(1<<-1) != 0 {returnfalse } .BitLength = len()*8 - int() .Bytes = returntrue}// ReadASN1BitStringAsBytes decodes an ASN.1 BIT STRING into out and advances. It is// an error if the BIT STRING is not a whole number of bytes. It reports// whether the read was successful.func ( *String) ( *[]byte) bool {varStringif !.ReadASN1(&, asn1.BIT_STRING) || len() == 0 {returnfalse } := [0]if != 0 {returnfalse } * = [1:]returntrue}// ReadASN1Bytes reads the contents of a DER-encoded ASN.1 element (not including// tag and length bytes) into out, and advances. The element must match the// given tag. It reports whether the read was successful.func ( *String) ( *[]byte, asn1.Tag) bool {return .ReadASN1((*String)(), )}// ReadASN1 reads the contents of a DER-encoded ASN.1 element (not including// tag and length bytes) into out, and advances. The element must match the// given tag. It reports whether the read was successful.//// Tags greater than 30 are not supported (i.e. low-tag-number format only).func ( *String) ( *String, asn1.Tag) bool {varasn1.Tagif !.ReadAnyASN1(, &) || != {returnfalse }returntrue}// ReadASN1Element reads the contents of a DER-encoded ASN.1 element (including// tag and length bytes) into out, and advances. The element must match the// given tag. It reports whether the read was successful.//// Tags greater than 30 are not supported (i.e. low-tag-number format only).func ( *String) ( *String, asn1.Tag) bool {varasn1.Tagif !.ReadAnyASN1Element(, &) || != {returnfalse }returntrue}// ReadAnyASN1 reads the contents of a DER-encoded ASN.1 element (not including// tag and length bytes) into out, sets outTag to its tag, and advances.// It reports whether the read was successful.//// Tags greater than 30 are not supported (i.e. low-tag-number format only).func ( *String) ( *String, *asn1.Tag) bool {return .readASN1(, , true/* skip header */)}// ReadAnyASN1Element reads the contents of a DER-encoded ASN.1 element// (including tag and length bytes) into out, sets outTag to is tag, and// advances. It reports whether the read was successful.//// Tags greater than 30 are not supported (i.e. low-tag-number format only).func ( *String) ( *String, *asn1.Tag) bool {return .readASN1(, , false/* include header */)}// PeekASN1Tag reports whether the next ASN.1 value on the string starts with// the given tag.func ( String) ( asn1.Tag) bool {iflen() == 0 {returnfalse }returnasn1.Tag([0]) == }// SkipASN1 reads and discards an ASN.1 element with the given tag. It// reports whether the operation was successful.func ( *String) ( asn1.Tag) bool {varStringreturn .ReadASN1(&, )}// ReadOptionalASN1 attempts to read the contents of a DER-encoded ASN.1// element (not including tag and length bytes) tagged with the given tag into// out. It stores whether an element with the tag was found in outPresent,// unless outPresent is nil. It reports whether the read was successful.func ( *String) ( *String, *bool, asn1.Tag) bool { := .PeekASN1Tag()if != nil { * = }if && !.ReadASN1(, ) {returnfalse }returntrue}// SkipOptionalASN1 advances s over an ASN.1 element with the given tag, or// else leaves s unchanged. It reports whether the operation was successful.func ( *String) ( asn1.Tag) bool {if !.PeekASN1Tag() {returntrue }varStringreturn .ReadASN1(&, )}// ReadOptionalASN1Integer attempts to read an optional ASN.1 INTEGER explicitly// tagged with tag into out and advances. If no element with a matching tag is// present, it writes defaultValue into out instead. Otherwise, it behaves like// ReadASN1Integer.func ( *String) ( interface{}, asn1.Tag, interface{}) bool {varboolvarStringif !.ReadOptionalASN1(&, &, ) {returnfalse }if ! {switch .(type) {case *int, *int8, *int16, *int32, *int64, *uint, *uint8, *uint16, *uint32, *uint64, *[]byte:reflect.ValueOf().Elem().Set(reflect.ValueOf())case *big.Int:if , := .(*big.Int); { .(*big.Int).Set() } else {panic("out points to big.Int, but defaultValue does not") }default:panic("invalid integer type") }returntrue }if !.ReadASN1Integer() || !.Empty() {returnfalse }returntrue}// ReadOptionalASN1OctetString attempts to read an optional ASN.1 OCTET STRING// explicitly tagged with tag into out and advances. If no element with a// matching tag is present, it sets "out" to nil instead. It reports// whether the read was successful.func ( *String) ( *[]byte, *bool, asn1.Tag) bool {varboolvarStringif !.ReadOptionalASN1(&, &, ) {returnfalse }if != nil { * = }if {varStringif !.ReadASN1(&, asn1.OCTET_STRING) || !.Empty() {returnfalse } * = } else { * = nil }returntrue}// ReadOptionalASN1Boolean attempts to read an optional ASN.1 BOOLEAN// explicitly tagged with tag into out and advances. If no element with a// matching tag is present, it sets "out" to defaultValue instead. It reports// whether the read was successful.func ( *String) ( *bool, asn1.Tag, bool) bool {varboolvarStringif !.ReadOptionalASN1(&, &, ) {returnfalse }if ! { * = returntrue }return .ReadASN1Boolean()}func ( *String) ( *String, *asn1.Tag, bool) bool {iflen(*) < 2 {returnfalse } , := (*)[0], (*)[1]if &0x1f == 0x1f {// ITU-T X.690 section 8.1.2 // // An identifier octet with a tag part of 0x1f indicates a high-tag-number // form identifier with two or more octets. We only support tags less than // 31 (i.e. low-tag-number form, single octet identifier).returnfalse }if != nil { * = asn1.Tag() }// ITU-T X.690 section 8.1.3 // // Bit 8 of the first length byte indicates whether the length is short- or // long-form.var , uint32// length includes headerLenif &0x80 == 0 {// Short-form length (section 8.1.3.4), encoded in bits 1-7. = uint32() + 2 = 2 } else {// Long-form length (section 8.1.3.5). Bits 1-7 encode the number of octets // used to encode the length. := & 0x7fvaruint32if == 0 || > 4 || len(*) < int(2+) {returnfalse } := String((*)[2 : 2+])if !.readUnsigned(&, int()) {returnfalse }// ITU-T X.690 section 10.1 (DER length forms) requires encoding the length // with the minimum number of octets.if < 128 {// Length should have used short-form encoding.returnfalse }if >>((-1)*8) == 0 {// Leading octet is 0. Length should have been at least one byte shorter.returnfalse } = 2 + uint32()if + < {// Overflow.returnfalse } = + }ifint() < 0 || !.ReadBytes((*[]byte)(), int()) {returnfalse }if && !.Skip(int()) {panic("cryptobyte: internal error") }returntrue}
The pages are generated with Goldsv0.7.0-preview. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds.