2018-06-01 15:53:24 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2018-06-01 16:19:35 +00:00
|
|
|
"bytes"
|
2018-06-01 15:53:24 +00:00
|
|
|
"fmt"
|
2018-06-01 16:19:35 +00:00
|
|
|
"io"
|
|
|
|
"io/ioutil"
|
2018-06-01 15:53:24 +00:00
|
|
|
|
2018-06-01 16:19:35 +00:00
|
|
|
"golang.org/x/crypto/openpgp"
|
|
|
|
"golang.org/x/crypto/openpgp/armor"
|
2018-11-02 20:40:47 +00:00
|
|
|
|
2019-08-04 10:21:14 +00:00
|
|
|
openssl "github.com/Luzifer/go-openssl/v3"
|
2018-06-01 15:53:24 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type decryptMethod func(body []byte, passphrase string) ([]byte, error)
|
|
|
|
|
|
|
|
func decryptMethodFromName(name string) (decryptMethod, error) {
|
|
|
|
switch name {
|
|
|
|
|
2018-06-01 16:19:35 +00:00
|
|
|
case "gpg-symmetric":
|
|
|
|
return decryptGPGSymmetric, nil
|
|
|
|
|
2018-06-01 15:53:24 +00:00
|
|
|
case "openssl-md5":
|
2018-11-02 20:40:47 +00:00
|
|
|
return decryptOpenSSL(openssl.DigestMD5Sum), nil
|
|
|
|
|
|
|
|
case "openssl-sha256":
|
|
|
|
return decryptOpenSSL(openssl.DigestSHA256Sum), nil
|
2018-06-01 15:53:24 +00:00
|
|
|
|
|
|
|
default:
|
|
|
|
return nil, fmt.Errorf("Decrypt method %q not found", name)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-06-01 16:19:35 +00:00
|
|
|
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)
|
|
|
|
}
|
|
|
|
|
2018-06-01 16:28:55 +00:00
|
|
|
var passwordRetry bool
|
2018-06-01 16:19:35 +00:00
|
|
|
md, err := openpgp.ReadMessage(msgReader, nil, func(keys []openpgp.Key, symmetric bool) ([]byte, error) {
|
2018-06-01 16:28:55 +00:00
|
|
|
if passwordRetry {
|
|
|
|
return nil, fmt.Errorf("Wrong passphrase supplied")
|
|
|
|
}
|
|
|
|
|
|
|
|
passwordRetry = true
|
2018-06-01 16:19:35 +00:00
|
|
|
return []byte(passphrase), nil
|
|
|
|
}, nil)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("Unable to decrypt message: %s", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return ioutil.ReadAll(md.UnverifiedBody)
|
|
|
|
}
|
|
|
|
|
2018-11-02 20:40:47 +00:00
|
|
|
func decryptOpenSSL(kdf openssl.DigestFunc) decryptMethod {
|
|
|
|
return func(body []byte, passphrase string) ([]byte, error) {
|
|
|
|
return openssl.New().DecryptBytes(cfg.Password, body, kdf)
|
|
|
|
}
|
2018-06-01 15:53:24 +00:00
|
|
|
}
|