forked from Luzifer/envrun
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdecryption.go
67 lines (52 loc) · 1.5 KB
/
decryption.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
package main
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"golang.org/x/crypto/openpgp"
"golang.org/x/crypto/openpgp/armor"
openssl "github.com/Luzifer/go-openssl"
)
type decryptMethod func(body []byte, passphrase string) ([]byte, error)
func decryptMethodFromName(name string) (decryptMethod, error) {
switch name {
case "gpg-symmetric":
return decryptGPGSymmetric, nil
case "openssl-md5":
return decryptOpenSSL(openssl.DigestMD5Sum), nil
case "openssl-sha256":
return decryptOpenSSL(openssl.DigestSHA256Sum), nil
default:
return nil, fmt.Errorf("Decrypt method %q not found", name)
}
}
func decryptGPGSymmetric(body []byte, passphrase string) ([]byte, error) {
var msgReader io.Reader
block, err := armor.Decode(bytes.NewReader(body))
switch err {
case nil:
msgReader = block.Body
case io.EOF:
msgReader = bytes.NewReader(body)
default:
return nil, fmt.Errorf("Unable to read armor: %s", err)
}
var passwordRetry bool
md, err := openpgp.ReadMessage(msgReader, nil, func(keys []openpgp.Key, symmetric bool) ([]byte, error) {
if passwordRetry {
return nil, fmt.Errorf("Wrong passphrase supplied")
}
passwordRetry = true
return []byte(passphrase), nil
}, nil)
if err != nil {
return nil, fmt.Errorf("Unable to decrypt message: %s", err)
}
return ioutil.ReadAll(md.UnverifiedBody)
}
func decryptOpenSSL(kdf openssl.DigestFunc) decryptMethod {
return func(body []byte, passphrase string) ([]byte, error) {
return openssl.New().DecryptBytes(cfg.Password, body, kdf)
}
}