From d01892150eed9d58210eb40b7c005d5fa8e93238 Mon Sep 17 00:00:00 2001 From: Gibheer Date: Sat, 1 Oct 2016 21:56:29 +0200 Subject: rework program flow This commit is a complete rebuild of pkictl. Before everything was all over the place and adding new commands was kind of a hassle. Now each command has its own file and can be adjusted on a command basis. Options are still used by the same name, but can now use different descriptions. --- pem.go | 71 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 pem.go (limited to 'pem.go') diff --git a/pem.go b/pem.go new file mode 100644 index 0000000..d3956f6 --- /dev/null +++ b/pem.go @@ -0,0 +1,71 @@ +package main + +// handle the pem decoding of files + +import ( + "encoding/pem" + "fmt" + "io" + "io/ioutil" + + "github.com/gibheer/pki" +) + +type ( + pemMap map[string][][]byte +) + +// Return the content of a section from the pem part. +// +// To get this working, the section must only be contained one time and nothing +// but the wanted section must exist. +func getSectionFromPem(pems pemMap, label string) ([]byte, error) { + if len(pems) > 1 { + return []byte{}, fmt.Errorf("too many entries in sign request file") + } + if len(pems[label]) > 1 { + return []byte{}, fmt.Errorf("too many sign requests found in file") + } + return pems[label][0], nil +} + +// parse the content of a file into a map of pem decoded bodies +func parseFile(file io.Reader) (pemMap, error) { + raw, err := ioutil.ReadAll(file) + if err != nil { + return nil, err + } + return parsePem(raw) +} + +// parse a pem encoded payload into a lookup map +// +// Returns a map of labels and content and the overall number of found items. +func parsePem(payload []byte) (pemMap, error) { + res := pemMap{} + rest := payload + rest_len := len(rest) + for len(rest) > 0 { + var block *pem.Block + block, rest = pem.Decode(rest) + if block == nil && len(rest) == rest_len { + return nil, fmt.Errorf("no pem encoding found") + } + res[block.Type] = append(res[block.Type], block.Bytes) + rest_len = len(rest) + } + return res, nil +} + +func writePem(o pki.Pemmer, w io.Writer) error { + marsh_pem, err := o.MarshalPem() + if err != nil { + return err + } + + _, err = marsh_pem.WriteTo(w) + if err != nil { + return err + } + return nil +} -- cgit v1.2.3-70-g09d2