This repository has been archived by the owner on Sep 29, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
main.go
74 lines (58 loc) · 1.47 KB
/
main.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
68
69
70
71
72
73
74
// Copyright Joyent, Inc.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
package obfuscate
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"errors"
"io"
)
func Obfuscate(data string, key string) (string, error) {
// We need a 32 byte key which sha256 is happy to give us
sum := sha256.Sum256([]byte(key))
c, err := aes.NewCipher(sum[:])
if err != nil {
return "", err
}
gcm, err := cipher.NewGCM(c)
if err != nil {
return "", err
}
nonce := make([]byte, gcm.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
return "", err
}
b := gcm.Seal(nonce, nonce, []byte(data), nil)
return base64.RawURLEncoding.EncodeToString(b), nil
}
func Deobfuscate(text string, key string) (string, error) {
data, err := base64.RawURLEncoding.DecodeString(text)
if err != nil {
return "", err
}
sum := sha256.Sum256([]byte(key))
c, err := aes.NewCipher(sum[:])
if err != nil {
return "", err
}
gcm, err := cipher.NewGCM(c)
if err != nil {
return "", err
}
nonceSize := gcm.NonceSize()
if len(data) < nonceSize {
return "", errors.New("ciphertext smaller than nonce")
}
nonce, ciphertext := data[:nonceSize], data[nonceSize:]
plain, err := gcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
return "", err
}
return string(plain), nil
}