-
Notifications
You must be signed in to change notification settings - Fork 3
/
encryption.go
111 lines (79 loc) · 2.24 KB
/
encryption.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
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
package core
import (
"crypto/aes"
"crypto/cipher"
"crypto/hmac"
"crypto/md5"
"crypto/rand"
"encoding/hex"
"io"
"github.com/awnumar/memguard"
"github.com/denisbrodbeck/machineid"
"github.com/rs/zerolog/log"
)
func CreateHash(key string) string {
log.Debug().Msg("create hash")
id, errID := machineid.ProtectedID("sts-wire")
if errID != nil {
panic(errID)
}
hasher := hmac.New(md5.New, []byte(id))
_, errWrite := hasher.Write([]byte(key))
if errWrite != nil {
panic(errWrite)
}
return hex.EncodeToString(hasher.Sum(nil))
}
func Encrypt(data []byte, password *memguard.Enclave) []byte {
log.Debug().Msg("encryption - open enclave")
passphrase, errOpenEnclave := password.Open()
if errOpenEnclave != nil {
memguard.SafePanic(errOpenEnclave)
}
defer passphrase.Destroy() // Destroy the copy when we return
log.Debug().Msg("encryption - create cipher")
block, errNewCiper := aes.NewCipher([]byte(CreateHash(string(passphrase.Bytes()))))
if errNewCiper != nil {
panic(errNewCiper)
}
log.Debug().Msg("encryption - create block")
gcm, errNewGCM := cipher.NewGCM(block)
if errNewGCM != nil {
panic(errNewGCM.Error())
}
nonce := make([]byte, gcm.NonceSize())
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
panic(err.Error())
}
log.Debug().Msg("encryption - encode")
ciphertext := gcm.Seal(nonce, nonce, data, nil)
return ciphertext
}
func Decrypt(data []byte, password *memguard.Enclave) []byte {
log.Debug().Msg("decryption - open enclave")
passphrase, errOpenEnclave := password.Open()
if errOpenEnclave != nil {
memguard.SafePanic(errOpenEnclave)
}
defer passphrase.Destroy() // Destroy the copy when we return
log.Debug().Msg("decryption - create key")
key := []byte(CreateHash(string(passphrase.Bytes())))
log.Debug().Msg("decryption - create cipher")
block, err := aes.NewCipher(key)
if err != nil {
panic(err.Error())
}
log.Debug().Msg("decryption - create block")
gcm, err := cipher.NewGCM(block)
if err != nil {
panic(err.Error())
}
nonceSize := gcm.NonceSize()
nonce, ciphertext := data[:nonceSize], data[nonceSize:]
log.Debug().Msg("decryption - decode")
plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
panic(err.Error())
}
return plaintext
}