-
Notifications
You must be signed in to change notification settings - Fork 3
/
secconf.go
73 lines (67 loc) · 1.8 KB
/
secconf.go
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
// Copyright secconf. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE-secconf file.
// Package secconf implements secconf encoding as specified in the following
// format:
//
// base64(gpg(gzip(data)))
//
package libconfd
import (
"bytes"
"compress/gzip"
"encoding/base64"
"io"
"io/ioutil"
"golang.org/x/crypto/openpgp"
)
// Deocde decodes data using the secconf codec.
func secconfDecode(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 secconfEncode(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
}