-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpgp.go
More file actions
64 lines (52 loc) · 1.8 KB
/
pgp.go
File metadata and controls
64 lines (52 loc) · 1.8 KB
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
package pgp
import (
"bytes"
"io"
"golang.org/x/crypto/openpgp"
"golang.org/x/crypto/openpgp/armor"
)
// KeyProvider returns a plain text armored pgp usable key.
// parameter scope is either public or private - indicates the usage of the key.
type KeyProvider func(recipientEMail string, scope string) (string, error)
// Encrypt pipes the plainMessage through ASCII-Armoring and pgp encryption
func Encrypt(plainMessage io.WriterTo, recipientMails []string, keyProvider KeyProvider) (io.WriterTo, error) {
// we have to scope public, since we want to encrypt against the public keys of given recipient
entities, err := getEntitiesByKeyProvider(recipientMails, keyProvider, "public")
if err != nil {
return nil, err
}
var encryptedOutputBuffer bytes.Buffer
armoringPipe, err := armor.Encode(&encryptedOutputBuffer, "PGP MESSAGE", nil)
if err != nil {
return nil, err
}
defer armoringPipe.Close()
encryptionWriter, err := openpgp.Encrypt(armoringPipe, entities, nil, &openpgp.FileHints{IsBinary: true}, nil)
if err != nil {
return nil, err
}
defer encryptionWriter.Close()
_, err = plainMessage.WriteTo(encryptionWriter)
if err != nil {
return nil, err
}
return &encryptedOutputBuffer, nil
}
// Sign returns a io.WriterTo "containing" the armored signature
func Sign(plainMessage io.WriterTo, senderMail string, provider KeyProvider, passphrase []byte) (io.WriterTo, error) {
// we need the private key for signing
entity, err := getSingleEntity(senderMail, provider, "private", passphrase)
if err != nil {
return nil, err
}
var inputBuffer bytes.Buffer
if _, err := plainMessage.WriteTo(&inputBuffer); err != nil {
return nil, err
}
writer := new(bytes.Buffer)
err = openpgp.ArmoredDetachSign(writer, entity, &inputBuffer, nil)
if err != nil {
return nil, err
}
return writer, nil
}