-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcryptext.go
More file actions
72 lines (58 loc) · 1.66 KB
/
cryptext.go
File metadata and controls
72 lines (58 loc) · 1.66 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
package cryptext
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/sha256"
"fmt"
"io"
)
func EncryptWithPhrase(phrase string, data string) (encryptedText string, err error) {
// The AES Cipher Engine requires a 32 byte key
// We're using SHA256 to generate a hash from the key
hash := sha256.Sum256([]byte(phrase))
// Create the AES Cipher Engine Block
CipherEngineBlock, err := aes.NewCipher(hash[:])
if err != nil {
return
}
// Create the AES Cipher Engine
CipherEngine, err := cipher.NewGCM(CipherEngineBlock)
if err != nil {
return
}
// Create the Nonce
nonce := make([]byte, CipherEngine.NonceSize())
// Verify the length of the nonce
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return "", err
}
// Encrypt the data
encryptedBytes := CipherEngine.Seal(nonce, nonce, []byte(data), nil)
fmt.Printf("%+v", string(encryptedBytes))
return string(encryptedBytes), nil
}
func DecryptWithPhrase(phrase string, data []byte) (encryptedText string, err error) {
// The AES Cipher Engine requires a 32 byte key
// We're using SHA256 to generate a hash from the key
hash := sha256.Sum256([]byte(phrase))
// Create the AES Cipher Engine Block
CipherEngineBlock, err := aes.NewCipher(hash[:])
if err != nil {
return
}
// Create the AES Cipher Engine
CipherEngine, err := cipher.NewGCM(CipherEngineBlock)
if err != nil {
return
}
// Create the Nonce from the data
nonceSize := CipherEngine.NonceSize()
nonce, ciphertext := data[:nonceSize], data[nonceSize:]
// Decrypt the data
decryptedBytes, err := CipherEngine.Open(nil, nonce, ciphertext, nil)
if err != nil {
return
}
return string(decryptedBytes), nil
}