-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathobfuscator.go
More file actions
62 lines (53 loc) · 1.72 KB
/
Copy pathobfuscator.go
File metadata and controls
62 lines (53 loc) · 1.72 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
package logger
import (
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"io"
"regexp"
)
var unobfuscateRex = regexp.MustCompile("(.*)!ENC!:{([^}]+)}(.*)")
// SetObfuscationKey sets the key used for obfuscation
func (l *Logger) SetObfuscationKey(key cipher.Block) {
l.obfuscationKey = key
}
// Obfuscate obfuscates the given string
func (l *Logger) Obfuscate(value string) string {
if l.obfuscationKey != nil {
var err error
var gcm cipher.AEAD
if gcm, err = cipher.NewGCM(l.obfuscationKey); err == nil {
nonce := make([]byte, gcm.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err == nil {
return "!ENC!:{" + base64.URLEncoding.EncodeToString(gcm.Seal(nonce, nonce, []byte(value), nil)) + "}"
}
}
l.Child("logger", "obfuscate").Errorf("Failed to obfuscate", err)
return value
}
l.Child("logger", "obfuscate").Warnf("WARNING, the next string will not be obfuscated because no obfuscation key was provided")
return value
}
// Unobfuscate the given string
func (l *Logger) Unobfuscate(value string) (unobfuscated string, err error) {
if l.obfuscationKey != nil {
if components := unobfuscateRex.FindStringSubmatch(value); len(components) == 4 {
var decoded []byte
if decoded, err = base64.URLEncoding.DecodeString(components[2]); err == nil {
var gcm cipher.AEAD
if gcm, err = cipher.NewGCM(l.obfuscationKey); err == nil {
var decrypted []byte
if len(decoded) >= gcm.NonceSize() {
nonce := decoded[:gcm.NonceSize()]
decoded = decoded[gcm.NonceSize():]
if decrypted, err = gcm.Open(nil, nonce, decoded, nil); err == nil {
return components[1] + string(decrypted) + components[3], nil
}
}
}
}
return value, err
}
}
return value, nil
}