func pemWrite(key *[32]byte, path string, pemType string, fileMode os.FileMode) {
	pemData := pemEncode(key, pemType)
	check(os.MkdirAll(filepath.Dir(path), 0775), "Failed to create directory %s", filepath.Dir(path))
	check(ioutil.WriteFile(path, []byte(pemData), fileMode), "Failed to write file %s", path)
}
Serialize a NaCL key to a PEM file
package main
import (
	"crypto/rand"
	"encoding/base64"
	"encoding/pem"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"path/filepath"
	"regexp"
	"strings"
	"golang.org/x/crypto/nacl/box"
)
var envelopeRegexp = regexp.MustCompile("ENC\\[(NACL|KMS),[a-zA-Z0-9+/=\\s]+\\]")
func asKey(data []byte) (*[32]byte, error) {
	if len(data) != 32 {
		return nil, errors.New("Expected a 32 byte key")
	}
	var key [32]byte
	copy(key[:], data[0:32])
	return &key, nil
}
func asNonce(data []byte) (*[24]byte, error) {
	if len(data) != 24 {
		return nil, errors.New("Expected a 24 byte nonce")
	}
	var key [24]byte
	copy(key[:], data[0:24])
	return &key, nil
}
func pemEncode(key *[32]byte, pemType string) string {
	return string(pem.EncodeToMemory(&pem.Block{Type: pemType, Bytes: key[:]}))
}
func pemDecode(encoded string) (*[32]byte, error) {
	mangled := strings.TrimSpace(encoded)
	if !strings.HasPrefix(mangled, "-----BEGIN") {
		mangled = fmt.Sprintf("-----BEGIN KEY-----\n%s\n-----END KEY-----", mangled)
	}
	pemBlock, _ := pem.Decode([]byte(mangled))
	if pemBlock == nil {
		return nil, errors.New("Failed to decode PEM block")
	}
	return asKey(pemBlock.Bytes)
}