From f5a9762b280cd525b807ea7dcd4a6beb7b1ea308 Mon Sep 17 00:00:00 2001 From: Kyle Isom Date: Thu, 14 Jan 2016 17:44:30 -0800 Subject: [PATCH] Add pem2bin, a utility for dumping the contents of PEM blocks. --- README.md | 1 + cmd/pem2bin/README | 8 ++++++++ cmd/pem2bin/main.go | 39 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 48 insertions(+) create mode 100644 cmd/pem2bin/README create mode 100644 cmd/pem2bin/main.go diff --git a/README.md b/README.md index 43c85ce..7896b3b 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,7 @@ Contents: certificate request. fragment/ Print a fragment of a file. jlp/ JSON linter/prettifier. + pem2bin/ Dump the binary body of a PEM-encoded block. pembody/ Print the body of a PEM certificate. showimp/ List the external (e.g. non-stdlib and outside the current working directory) imports for a Go file. diff --git a/cmd/pem2bin/README b/cmd/pem2bin/README new file mode 100644 index 0000000..9f7cee6 --- /dev/null +++ b/cmd/pem2bin/README @@ -0,0 +1,8 @@ +pem2bin + +This is a utility that strips the PEM-encoding from a file and dumps +the binary body to disk. The resulting filename is the original pathname +with ".bin" appended. Note that only the first PEM block in a file will +be decoded. + +Usage: pem2bin paths* diff --git a/cmd/pem2bin/main.go b/cmd/pem2bin/main.go new file mode 100644 index 0000000..b7594a8 --- /dev/null +++ b/cmd/pem2bin/main.go @@ -0,0 +1,39 @@ +package main + +import ( + "encoding/pem" + "flag" + "fmt" + "io/ioutil" + "os" +) + +var ext = ".bin" + +func stripPEM(path string) error { + data, err := ioutil.ReadFile(path) + if err != nil { + return err + } + + p, rest := pem.Decode(data) + if len(rest) != 0 { + fmt.Fprintf(os.Stderr, "[WARNING] extra data in PEM file\n") + fmt.Fprintf(os.Stderr, " (only the first object will be decoded)\n") + } + + return ioutil.WriteFile(path+ext, p.Bytes, 0644) +} + +func main() { + flag.Parse() + + for _, path := range flag.Args() { + err := stripPEM(path) + if err != nil { + fmt.Fprintf(os.Stderr, "processing %s failed: %v\n", path, err) + } else { + fmt.Println(path, "->", path+ext) + } + } +}