...

Source file src/encoding/pem/example_test.go

Documentation: encoding/pem

		 1  // Copyright 2016 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 pem_test
		 6  
		 7  import (
		 8  	"crypto/x509"
		 9  	"encoding/pem"
		10  	"fmt"
		11  	"log"
		12  	"os"
		13  )
		14  
		15  func ExampleDecode() {
		16  	var pubPEMData = []byte(`
		17  -----BEGIN PUBLIC KEY-----
		18  MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAlRuRnThUjU8/prwYxbty
		19  WPT9pURI3lbsKMiB6Fn/VHOKE13p4D8xgOCADpdRagdT6n4etr9atzDKUSvpMtR3
		20  CP5noNc97WiNCggBjVWhs7szEe8ugyqF23XwpHQ6uV1LKH50m92MbOWfCtjU9p/x
		21  qhNpQQ1AZhqNy5Gevap5k8XzRmjSldNAFZMY7Yv3Gi+nyCwGwpVtBUwhuLzgNFK/
		22  yDtw2WcWmUU7NuC8Q6MWvPebxVtCfVp/iQU6q60yyt6aGOBkhAX0LpKAEhKidixY
		23  nP9PNVBvxgu3XZ4P36gZV6+ummKdBVnc3NqwBLu5+CcdRdusmHPHd5pHf4/38Z3/
		24  6qU2a/fPvWzceVTEgZ47QjFMTCTmCwNt29cvi7zZeQzjtwQgn4ipN9NibRH/Ax/q
		25  TbIzHfrJ1xa2RteWSdFjwtxi9C20HUkjXSeI4YlzQMH0fPX6KCE7aVePTOnB69I/
		26  a9/q96DiXZajwlpq3wFctrs1oXqBp5DVrCIj8hU2wNgB7LtQ1mCtsYz//heai0K9
		27  PhE4X6hiE0YmeAZjR0uHl8M/5aW9xCoJ72+12kKpWAa0SFRWLy6FejNYCYpkupVJ
		28  yecLk/4L1W0l6jQQZnWErXZYe0PNFcmwGXy1Rep83kfBRNKRy5tvocalLlwXLdUk
		29  AIU+2GKjyT3iMuzZxxFxPFMCAwEAAQ==
		30  -----END PUBLIC KEY-----
		31  and some more`)
		32  
		33  	block, rest := pem.Decode(pubPEMData)
		34  	if block == nil || block.Type != "PUBLIC KEY" {
		35  		log.Fatal("failed to decode PEM block containing public key")
		36  	}
		37  
		38  	pub, err := x509.ParsePKIXPublicKey(block.Bytes)
		39  	if err != nil {
		40  		log.Fatal(err)
		41  	}
		42  
		43  	fmt.Printf("Got a %T, with remaining data: %q", pub, rest)
		44  	// Output: Got a *rsa.PublicKey, with remaining data: "and some more"
		45  }
		46  
		47  func ExampleEncode() {
		48  	block := &pem.Block{
		49  		Type: "MESSAGE",
		50  		Headers: map[string]string{
		51  			"Animal": "Gopher",
		52  		},
		53  		Bytes: []byte("test"),
		54  	}
		55  
		56  	if err := pem.Encode(os.Stdout, block); err != nil {
		57  		log.Fatal(err)
		58  	}
		59  	// Output:
		60  	// -----BEGIN MESSAGE-----
		61  	// Animal: Gopher
		62  	//
		63  	// dGVzdA==
		64  	// -----END MESSAGE-----
		65  }
		66  

View as plain text