aboutsummaryrefslogtreecommitdiff
path: root/sign.go
blob: 37a506f4df1395c996395a81f65b6650b0b97058 (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
92
93
94
95
96
package main

import (
	"flag"
	"io/ioutil"

	"dim13.org/signify/ask"
	"dim13.org/signify/file"
	"dim13.org/signify/key"
)

// Usage: signify -S [-ez] [-x sigfile] -s seckey -m message

func sign(args []string) error {
	opts := flag.NewFlagSet("sign", flag.ExitOnError)
	var (
		embedded = opts.Bool("e", false, "Embed the message")
		zip      = opts.Bool("z", false, "Sign gzip archive") // TODO
		sigFile  = opts.String("x", "", "Signature file")
		secFile  = opts.String("s", "", "Secret file (required)")
		msgFile  = opts.String("m", "", "Message file (required)")
	)
	opts.Parse(args)
	if *secFile == "" || *msgFile == "" {
		opts.Usage()
		return nil
	}
	if *sigFile == "" {
		*sigFile = file.SigName(*msgFile)
	}

	switch {
	case *zip && *embedded:
		return ErrEZ
	case *zip:
		if err := signGzip(*secFile, *msgFile, *sigFile); err != nil {
			return err
		}
	case *embedded:
		if err := signEmbedded(*secFile, *msgFile, *sigFile); err != nil {
			return err
		}
	default:
		if err := signPlain(*secFile, *msgFile, *sigFile); err != nil {
			return err
		}
	}

	return nil
}

func signPlain(secFile, msgFile, sigFile string) error {
	sec, err := openSec(secFile)
	if err != nil {
		return err
	}
	msg, err := ioutil.ReadFile(msgFile)
	if err != nil {
		return err
	}
	sig := sec.Sign(msg)
	comment := file.VerifyWith(secFile)
	return file.EncodeFile(sigFile, file.ModeSig, sig, comment, nil)
}

func signEmbedded(secFile, msgFile, sigFile string) error {
	sec, err := openSec(secFile)
	if err != nil {
		return err
	}
	msg, err := ioutil.ReadFile(msgFile)
	if err != nil {
		return err
	}
	sig := sec.Sign(msg)
	comment := file.VerifyWith(secFile)
	return file.EncodeFile(sigFile, file.ModeSig, sig, comment, msg)
}

func signGzip(secFile, msgFile, sigFile string) error {
	return nil
}

func openSec(fname string) (*key.Sec, error) {
	sec := new(key.Sec)
	if _, _, err := file.DecodeFile(fname, sec); err != nil {
		return nil, err
	}
	if err := sec.Crypt(ask.Passphrase{}); err != nil {
		return nil, err
	}
	if err := sec.Validate(); err != nil {
		return nil, err
	}
	return sec, nil
}