aboutsummaryrefslogtreecommitdiff
path: root/pem.go
diff options
context:
space:
mode:
authorGibheer <gibheer+git@zero-knowledge.org>2016-10-01 21:56:29 +0200
committerGibheer <gibheer+git@zero-knowledge.org>2016-10-01 21:56:29 +0200
commitd01892150eed9d58210eb40b7c005d5fa8e93238 (patch)
treef9d37f3d5b4f0d9afd01755801826713f47d83c3 /pem.go
parentfaaf7d8859895767b5e64d32c14d561d6fdb5a14 (diff)
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.
Diffstat (limited to 'pem.go')
-rw-r--r--pem.go71
1 files changed, 71 insertions, 0 deletions
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
+}