aboutsummaryrefslogtreecommitdiff
path: root/io.go
blob: 56cc6899deec800c6cc024ed4f8f7fd2ec24611d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package main

// handle all io and de/encoding of data

import (
	"encoding/pem"
	"errors"
	"io/ioutil"
)

var (
	ErrBlockNotFound = errors.New("block not found")
)

// load a pem section from a file
func readSectionFromFile(path, btype string) ([]byte, error) {
	raw, err := readFile(path)
	if err != nil {
		return raw, err
	}

	return decodeSection(raw, btype)
}

// read a file completely and report possible errors
func readFile(path string) ([]byte, error) {
	raw, err := ioutil.ReadFile(path)
	if err != nil {
		return EmptyByteArray, err
	}
	return raw, nil
}

// decode a pem encoded file and search for the specified section
func decodeSection(data []byte, btype string) ([]byte, error) {
	rest := data
	for len(rest) > 0 {
		var block *pem.Block
		block, rest = pem.Decode(rest)
		if block.Type == btype {
			return block.Bytes, nil
		}
	}
	return EmptyByteArray, ErrBlockNotFound
}