aboutsummaryrefslogtreecommitdiff
path: root/pkg/signatures/signify/signify.go
blob: 6dbbf07310489f4f586f665c6ef262b57661354f (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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package signify

import (
	"bytes"
	"encoding/base64"
	"fmt"
	"io"
	"io/ioutil"

	"git.sigsum.org/sigsum-lib-go/pkg/types"
)

type Parser struct{}

func (p *Parser) SignatureSuffix() string {
	return ".sig"
}

func (p *Parser) PublicKey(r io.Reader) (*types.PublicKey, error) {
	b, err := ioutil.ReadAll(r)
	if err != nil {
		return nil, fmt.Errorf("signify: read failed: %v", err)
	}
	var pub types.PublicKey
	if err := parse(pub[:], b); err != nil {
		return nil, fmt.Errorf("signify: %v", err)
	}
	return &pub, nil
}

func (p *Parser) Signature(r io.Reader) (*types.Signature, error) {
	b, err := ioutil.ReadAll(r)
	if err != nil {
		return nil, fmt.Errorf("signify: read failed: %v", err)
	}
	var sig types.Signature
	if err := parse(sig[:], b); err != nil {
		return nil, fmt.Errorf("signify: %v", err)
	}
	return &sig, nil
}

func parse(dst, lines []byte) error {
	commentLine, dataLine, err := parseLines(lines)
	if err != nil {
		return fmt.Errorf("invalid: %v", err)
	}
	if err := parseCommentLine(commentLine); err != nil {
		return fmt.Errorf("invalid: %v", err)
	}
	if err := parseDataLine(dst, dataLine); err != nil {
		return fmt.Errorf("invalid: %v", err)
	}
	return nil
}

func parseLines(lines []byte) ([]byte, []byte, error) {
	split := bytes.Split(lines, []byte("\n"))
	if len(split) != 3 {
		return nil, nil, fmt.Errorf("number of lines")
	}
	return split[0], split[1], nil
}

func parseCommentLine(line []byte) error {
	if !bytes.HasPrefix(line, []byte("untrusted comment: ")) {
		return fmt.Errorf("no untrusted comment")
	}
	return nil
}

func parseDataLine(dst, line []byte) error {
	data, err := base64.StdEncoding.DecodeString(string(line))
	if err != nil {
		return fmt.Errorf("base64 encoding")
	}
	if len(data) < 2 || !bytes.Equal(data[:2], []byte("Ed")) {
		return fmt.Errorf("algorithm")
	}
	data = data[2:]
	if len(data) < 8 {
		return fmt.Errorf("random fingerprint")
	}
	data = data[8:]
	if len(data) != len(dst) {
		return fmt.Errorf("data length")
	}

	copy(dst[:], data)
	return nil
}