forked from ProtonMail/gopenpgp
/
armor.go
69 lines (58 loc) · 1.79 KB
/
armor.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
// Package armor contains a set of helper methods for armoring and unarmoring
// data.
package armor
import (
"bytes"
"io"
"io/ioutil"
"github.com/klische/gopenpgp/v2/constants"
"github.com/klische/gopenpgp/v2/internal"
"golang.org/x/crypto/openpgp/armor"
)
// ArmorKey armors input as a public key.
func ArmorKey(input []byte) (string, error) {
return ArmorWithType(input, constants.PublicKeyHeader)
}
// ArmorWithTypeBuffered returns a io.WriteCloser which, when written to, writes
// armored data to w with the given armorType.
func ArmorWithTypeBuffered(w io.Writer, armorType string) (io.WriteCloser, error) {
return armor.Encode(w, armorType, nil)
}
// ArmorWithType armors input with the given armorType.
func ArmorWithType(input []byte, armorType string) (string, error) {
return armorWithTypeAndHeaders(input, armorType, internal.ArmorHeaders)
}
// ArmorWithTypeAndCustomHeaders armors input with the given armorType and
// headers.
func ArmorWithTypeAndCustomHeaders(input []byte, armorType, version, comment string) (string, error) {
headers := make(map[string]string)
if version != "" {
headers["Version"] = version
}
if comment != "" {
headers["Comment"] = comment
}
return armorWithTypeAndHeaders(input, armorType, headers)
}
// Unarmor unarmors an armored input into a byte array.
func Unarmor(input string) ([]byte, error) {
b, err := internal.Unarmor(input)
if err != nil {
return nil, err
}
return ioutil.ReadAll(b.Body)
}
func armorWithTypeAndHeaders(input []byte, armorType string, headers map[string]string) (string, error) {
var b bytes.Buffer
w, err := armor.Encode(&b, armorType, headers)
if err != nil {
return "", err
}
if _, err = w.Write(input); err != nil {
return "", err
}
if err := w.Close(); err != nil {
return "", err
}
return b.String(), nil
}