-
Notifications
You must be signed in to change notification settings - Fork 0
/
crypto.go
64 lines (54 loc) · 1.32 KB
/
crypto.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
package ezpwd
import (
"fmt"
"io"
"golang.org/x/crypto/openpgp"
)
type Crypto struct {
keyPass []byte
}
func NewCrypto(pwd []byte) (*Crypto, error) {
return &Crypto{
keyPass: pwd,
}, nil
}
type KeyWriter io.Writer
type CryptoInterface interface {
Encrypt(in io.Reader, out io.Writer) error
Decrypt(in io.Reader, out io.Writer) error
}
func (cr *Crypto) Encrypt(in io.Reader, out io.Writer) error {
w, err := openpgp.SymmetricallyEncrypt(out, cr.keyPass, nil, nil)
if err != nil {
return fmt.Errorf("can't encrypt the message: %w", err)
}
if _, err = io.Copy(w, in); err != nil {
return fmt.Errorf("can't copy encrypted message: %w", err)
}
return w.Close()
}
var (
noSymmetric = fmt.Errorf("Symmetric not set")
wrongPass = fmt.Errorf("Wrong password")
)
func (cr *Crypto) Decrypt(in io.Reader, out io.Writer) error {
read := false
md, err := openpgp.ReadMessage(in, nil, func(keys []openpgp.Key, symmetric bool) ([]byte, error) {
if !symmetric {
return nil, noSymmetric
}
if read {
return nil, wrongPass
}
read = true
return cr.keyPass, nil
}, nil)
if err != nil {
return fmt.Errorf("can't decrypt message : %w", err)
}
if _, err := io.Copy(out, md.UnverifiedBody); err != nil {
return fmt.Errorf("can't transfer decrypted message : %w", err)
}
return nil
}
var _ CryptoInterface = &Crypto{}