aboutsummaryrefslogtreecommitdiff
path: root/zsig/header.go
blob: aa1c13b7450365f3ddebd84f0013343fc7339c78 (plain)
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package zsig

import (
	"bufio"
	"encoding/hex"
	"fmt"
	"io"
	"strconv"
	"strings"
	"time"
)

type ZHeader struct {
	Date      time.Time
	KeyFile   string
	Alg       string
	BlockSize int
	Sums      [][]byte
}

const (
	DefaultAlg       = "SHA512/256"
	DefaultBlockSize = 65536
)

func (h ZHeader) Print(w io.Writer) error {
	fmt.Fprintf(w, "date=%v\n", h.Date.Format(time.RFC3339))
	fmt.Fprintf(w, "key=%v\n", h.KeyFile)
	fmt.Fprintf(w, "algorithm=%v\n", h.Alg)
	fmt.Fprintf(w, "blocksize=%v\n\n", h.BlockSize)
	for _, sum := range h.Sums {
		fmt.Fprintf(w, "%x\n", sum)
	}
	return nil
}

func Parse(r io.Reader) (ZHeader, error) {
	var h ZHeader
	s := bufio.NewScanner(r)
	for s.Scan() {
		line := s.Text()
		switch {
		case strings.HasPrefix(line, "date="):
			t, err := time.Parse(time.RFC3339, line[5:])
			if err != nil {
				return ZHeader{}, err
			}
			h.Date = t
		case strings.HasPrefix(line, "key="):
			h.KeyFile = line[4:]
		case strings.HasPrefix(line, "algorithm="):
			h.Alg = line[10:]
		case strings.HasPrefix(line, "blocksize="):
			i, err := strconv.Atoi(line[10:])
			if err != nil {
				return ZHeader{}, err
			}
			h.BlockSize = i
		case line == "":
			for s.Scan() {
				line = s.Text()
				sum, err := hex.DecodeString(line)
				if err != nil {
					return ZHeader{}, err
				}
				h.Sums = append(h.Sums, sum)
			}
		}
	}
	return h, s.Err()
}