This repository has been archived by the owner on Mar 11, 2021. It is now read-only.
/
decode.go
61 lines (53 loc) · 1.67 KB
/
decode.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
package auth
import (
"bytes"
"encoding/base64"
"errors"
"io/ioutil"
"golang.org/x/crypto/openpgp"
)
// Decode a function to decode a given value
type Decode func(data string) (string, error)
// PlainText is a Decode function that can be used to fetch tokens that are not encrypted.
// Simply return the same token back
func PlainText(token string) (string, error) {
return token, nil
}
// NewGPGDecypter takes a passphrase and returns a GPG based Decypter decode function
func NewGPGDecypter(passphrase string) Decode {
return func(body string) (string, error) {
return gpgDecyptToken(body, passphrase)
}
}
// GPGDecyptToken decrypts a Base64 encoded GPG un armored encrypted string
// using provided passphrase.
// on Linux:
// echo -n "SuperSecret" | gpg --symmetric --cipher-algo AES256 | base64 -w0
// on macOS:
// echo -n "SuperSecret" | gpg --symmetric --cipher-algo AES256 | base64
// and keep the result then use a Docker container to run:
// echo -n $TOKEN | base64 -d | base64 -w0
// in any case, don't forget the `-n` arg in the `echo` command!
func gpgDecyptToken(base64Body, passphrase string) (string, error) {
decodedEnc, err := base64.StdEncoding.DecodeString(base64Body)
if err != nil {
return "", err
}
decbuf := bytes.NewBuffer(decodedEnc)
firstCall := true
md, err := openpgp.ReadMessage(decbuf, nil, func(keys []openpgp.Key, symmetric bool) ([]byte, error) {
if firstCall {
firstCall = false
return []byte(passphrase), nil
}
return nil, errors.New("unable to decrypt token with given key")
}, nil)
if err != nil {
return "", err
}
bytes, err := ioutil.ReadAll(md.UnverifiedBody)
if err != nil {
return "", err
}
return string(bytes), nil
}