summaryrefslogtreecommitdiffstats
path: root/vendor/github.com/xordataexchange/crypt/encoding/secconf/secconf.go
blob: 6e94565d737a3f77f0d09c03463b9517aaee7806 (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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// Package secconf implements secconf encoding as specified in the following
// format:
//
//   base64(gpg(gzip(data)))
//
package secconf

import (
	"bytes"
	"compress/gzip"
	"encoding/base64"
	"io"
	"io/ioutil"

	"golang.org/x/crypto/openpgp"
)

// Deocde decodes data using the secconf codec.
func Decode(data []byte, secertKeyring io.Reader) ([]byte, error) {
	decoder := base64.NewDecoder(base64.StdEncoding, bytes.NewBuffer(data))
	entityList, err := openpgp.ReadArmoredKeyRing(secertKeyring)
	if err != nil {
		return nil, err
	}
	md, err := openpgp.ReadMessage(decoder, entityList, nil, nil)
	if err != nil {
		return nil, err
	}
	gzReader, err := gzip.NewReader(md.UnverifiedBody)
	if err != nil {
		return nil, err
	}
	defer gzReader.Close()
	bytes, err := ioutil.ReadAll(gzReader)
	if err != nil {
		return nil, err
	}
	return bytes, nil
}

// Encode encodes data to a base64 encoded using the secconf codec.
// data is encrypted with all public keys found in the supplied keyring.
func Encode(data []byte, keyring io.Reader) ([]byte, error) {
	entityList, err := openpgp.ReadArmoredKeyRing(keyring)
	if err != nil {
		return nil, err
	}
	buffer := new(bytes.Buffer)
	encoder := base64.NewEncoder(base64.StdEncoding, buffer)
	pgpWriter, err := openpgp.Encrypt(encoder, entityList, nil, nil, nil)
	if err != nil {
		return nil, err
	}
	gzWriter := gzip.NewWriter(pgpWriter)
	if _, err := gzWriter.Write(data); err != nil {
		return nil, err
	}
	if err := gzWriter.Close(); err != nil {
		return nil, err
	}
	if err := pgpWriter.Close(); err != nil {
		return nil, err
	}
	if err := encoder.Close(); err != nil {
		return nil, err
	}
	return buffer.Bytes(), nil
}