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.
5 package cryptobyte_test
10 "golang.org/x/crypto/cryptobyte"
13 func ExampleString_lengthPrefixed() {
14 // This is an example of parsing length-prefixed data (as found in, for
15 // example, TLS). Imagine a 16-bit prefixed series of 8-bit prefixed
18 input := cryptobyte.String([]byte{0, 12, 5, 'h', 'e', 'l', 'l', 'o', 5, 'w', 'o', 'r', 'l', 'd'})
21 var values cryptobyte.String
22 if !input.ReadUint16LengthPrefixed(&values) ||
28 var value cryptobyte.String
29 if !values.ReadUint8LengthPrefixed(&value) {
33 result = append(result, string(value))
36 // Output: []string{"hello", "world"}
37 fmt.Printf("%#v\n", result)
40 func ExampleString_asn1() {
41 // This is an example of parsing ASN.1 data that looks like:
43 // version [6] INTEGER DEFAULT 0
47 input := cryptobyte.String([]byte{0x30, 12, 0xa6, 3, 2, 1, 2, 4, 5, 'h', 'e', 'l', 'l', 'o'})
51 data, inner, versionBytes cryptobyte.String
54 if !input.ReadASN1(&inner, cryptobyte.Tag(asn1.TagSequence).Constructed()) ||
56 !inner.ReadOptionalASN1(&versionBytes, &haveVersion, cryptobyte.Tag(6).Constructed().ContextSpecific()) ||
57 (haveVersion && !versionBytes.ReadASN1Integer(&version)) ||
58 (haveVersion && !versionBytes.Empty()) ||
59 !inner.ReadASN1(&data, asn1.TagOctetString) ||
64 // Output: haveVersion: true, version: 2, data: hello
65 fmt.Printf("haveVersion: %t, version: %d, data: %s\n", haveVersion, version, string(data))
68 func ExampleBuilder_asn1() {
69 // This is an example of building ASN.1 data that looks like:
71 // version [6] INTEGER DEFAULT 0
76 data := []byte("hello")
77 const defaultVersion = 0
79 var b cryptobyte.Builder
80 b.AddASN1(cryptobyte.Tag(asn1.TagSequence).Constructed(), func(b *cryptobyte.Builder) {
81 if version != defaultVersion {
82 b.AddASN1(cryptobyte.Tag(6).Constructed().ContextSpecific(), func(b *cryptobyte.Builder) {
83 b.AddASN1Int64(version)
86 b.AddASN1OctetString(data)
89 result, err := b.Bytes()
94 // Output: 300ca603020102040568656c6c6f
95 fmt.Printf("%x\n", result)
98 func ExampleBuilder_lengthPrefixed() {
99 // This is an example of building length-prefixed data (as found in,
100 // for example, TLS). Imagine a 16-bit prefixed series of 8-bit
102 input := []string{"hello", "world"}
104 var b cryptobyte.Builder
105 b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
106 for _, value := range input {
107 b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) {
108 b.AddBytes([]byte(value))
113 result, err := b.Bytes()
118 // Output: 000c0568656c6c6f05776f726c64
119 fmt.Printf("%x\n", result)