aboutsummaryrefslogtreecommitdiff
path: root/sign.go
blob: 56e7e03c721730026e0780a397a9f1aad303f651 (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
package main

import (
	"errors"
	"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")
		encFile  = opts.String("s", "", "Secret file (required)")
		msgFile  = opts.String("m", "", "Message file (required)")
	)
	opts.Parse(args)
	if *embedded && *zip {
		return errors.New("can't combine -e and -z options")
	}
	if *encFile == "" || *msgFile == "" {
		opts.Usage()
		return nil
	}
	if *sigFile == "" {
		*sigFile = file.SigName(*msgFile)
	}
	_ = zip // TODO

	encKey, err := OpenEnc(*encFile)
	if err != nil {
		return err
	}
	body, err := ioutil.ReadFile(*msgFile)
	if err != nil {
		return err
	}
	sig := encKey.Sign(body)
	raw, err := sig.MarshalBinary()
	if err != nil {
		return err
	}
	block := &file.Block{
		Comment: file.VerifyWith(*encFile),
		Bytes:   raw,
	}
	if *embedded {
		block.Message = body // TODO implement as acting on io.Writer
	}
	if err := file.EncodeFile(*sigFile, file.SigMode, block); err != nil {
		return err
	}
	return nil
}

func OpenEnc(fname string) (*key.Enc, error) {
	block, err := file.DecodeFile(fname)
	if err != nil {
		return nil, err
	}
	return key.ParseEnc(block.Bytes, ask.Passphrase{})
}