-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecrypt.go
More file actions
175 lines (155 loc) · 4.23 KB
/
decrypt.go
File metadata and controls
175 lines (155 loc) · 4.23 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
package dotenvx
import (
"bufio"
"encoding/base64"
"fmt"
"os"
"strings"
ecies "github.com/ecies/go/v2"
)
var (
Debug bool
)
type EnvFile struct {
Path string
Key *ecies.PrivateKey
}
type EnvVar struct {
Name string
Value string
}
// searches for DOTENV_PRIVATE_KEY* environment variables, returns first valid file/key pair
func getEnvFile() (envFile EnvFile, err error) {
if Debug {
fmt.Println("Checking for private key in environment")
}
// Search for valid key / with corresponding EnvFile
keysInEnv := 0
for _, env := range os.Environ() {
if strings.HasPrefix(env, "DOTENV_PRIVATE_KEY") {
parts := strings.SplitN(env, "=", 2)
if len(parts) != 2 || parts[1] == "" {
continue
}
keysInEnv++
varName, keyHex := parts[0], parts[1]
// Map DOTENV_PRIVATE_KEY_SUFFIX to .env.suffix
fileName := ""
if varName == "DOTENV_PRIVATE_KEY" {
fileName = ".env"
} else if strings.HasPrefix(varName, "DOTENV_PRIVATE_KEY_") {
suffix := strings.TrimPrefix(varName, "DOTENV_PRIVATE_KEY_")
// Convert suffix to lowercase, replace _ with .
suffix = strings.ToLower(suffix)
suffix = strings.ReplaceAll(suffix, "_", ".")
fileName = ".env." + suffix
}
if Debug {
fmt.Printf("Found key %s and file %s\n", varName, fileName)
if keysInEnv > 1 {
fmt.Println("WARNING: Multiple private keys found in environment!")
}
}
if _, err := os.Stat(fileName); err == nil {
if privateKey, err := ecies.NewPrivateKeyFromHex(keyHex); err == nil {
return EnvFile{fileName, privateKey}, nil
} else if Debug {
fmt.Println("Invalid key format")
}
} else if Debug {
fmt.Printf("Unable to open: %s\n", fileName)
}
}
}
// No valid file/key combination found
if keysInEnv == 0 {
if Debug {
fmt.Println("No key found")
}
err = fmt.Errorf("No key found")
} else {
err = fmt.Errorf("No valid file/key combination found")
}
return envFile, err
}
func decryptSecret(privateKey *ecies.PrivateKey, base64ciper string) string {
cipherBytes, _ := base64.StdEncoding.DecodeString(base64ciper)
plainBytes, _ := ecies.Decrypt(privateKey, cipherBytes)
return string(plainBytes)
}
func parseEnvVar(line string, privateKey *ecies.PrivateKey, name string) EnvVar {
if offset := strings.Index(line, "="); offset > 0 && line[0] != '#' {
varName := strings.TrimPrefix(line[:offset], "export ")
if varName != name && name != "" {
return EnvVar{}
}
value := line[offset+1:]
value = strings.TrimSpace(value)
if (strings.HasPrefix(value, `"`) && strings.HasSuffix(value, `"`)) ||
(strings.HasPrefix(value, `'`) && strings.HasSuffix(value, `'`)) {
value = value[1 : len(value)-1]
}
if strings.HasPrefix(value, "encrypted:") {
value = decryptSecret(privateKey, value[10:])
}
return EnvVar{varName, value}
}
return EnvVar{}
}
func getEnvVars(envFile *EnvFile, name string) (vars []EnvVar, err error) {
file, err := os.Open(envFile.Path)
if err != nil {
if Debug {
fmt.Printf("Unable to open %s: %v\n", envFile.Path, err)
}
return []EnvVar{}, err
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
envVar := parseEnvVar(scanner.Text(), envFile.Key, name)
if envVar.Name == "" {
continue
}
vars = append(vars, envVar)
}
return vars, scanner.Err()
}
func Getenv(key string) string {
envFile, err := getEnvFile()
if Debug && (envFile.Key == nil || err != nil) {
fmt.Printf("Error finding envFile (%+v): %+v\n", envFile, err)
}
if err != nil {
return ""
}
vars, err := getEnvVars(&envFile, key)
if Debug && (len(vars) != 1 || err != nil) {
fmt.Printf("Error retrieving (%s) (%d values): %+v\n", key, len(vars), err)
}
if err != nil || len(vars) == 0 {
return ""
}
return vars[0].Value
}
func Environ() []string {
envFile, err := getEnvFile()
if Debug && (envFile.Key == nil || err != nil) {
fmt.Printf("Error finding envFile (%+v): %+v\n", envFile, err)
}
if err != nil {
return []string{}
}
vars, err := getEnvVars(&envFile, "")
if Debug && (len(vars) == 0 || err != nil) {
fmt.Printf("Error retrieving all values (%d found): %+v\n", len(vars), err)
}
if err != nil {
return []string{}
}
env := make([]string, 0, len(vars))
for _, v := range vars {
env = append(env, v.Name+"="+v.Value)
}
return env
}