-
Notifications
You must be signed in to change notification settings - Fork 0
/
encrypter.go
57 lines (50 loc) · 1.51 KB
/
encrypter.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
package cryptonx
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/hex"
"fmt"
"io"
"log"
)
/*
Encrypter Encrypts text based on AES Algorythim and return the encrypted text and his nonce
*/
func Encrypter(key string, text string) (encryptedText string, nonce string, err error) {
err = nil
nonceTemp := make([]byte, 12)
if _, err = io.ReadFull(rand.Reader, nonceTemp); err != nil {
fmt.Printf("[Encrypter] Error during nonce generation: [%s]\n", err.Error())
return
}
aesgcm, err := GetAEAD(key)
if err != nil {
fmt.Printf("[Encrypter] Error during AEAD generation: [%s]\n", err.Error())
return
}
encryptedText = fmt.Sprintf("%x", aesgcm.Seal(nil, nonceTemp, []byte(text), nil))
nonce = fmt.Sprintf("%x", nonceTemp)
return
}
//EncryptWithNonce it encrypts data and embbeded the nonce within the encrypted data
func EncryptWithNonce(plainText string, key string) (cypherText string, err error) {
err = nil
c, err := aes.NewCipher([]byte(key))
if err != nil {
log.Printf("[EncryptWithNonce] Error during Cypher generation. Error: %s\n", err.Error())
return
}
gcm, err := cipher.NewGCM(c)
if err != nil {
log.Printf("[EncryptWithNonce] Error during GCM generation. Error: %s\n", err.Error())
return
}
nonce := make([]byte, gcm.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
log.Printf("[EncryptWithNonce] Error during nonce reading. Error: %s\n", err.Error())
return
}
cypherText = hex.EncodeToString(gcm.Seal(nonce, nonce, []byte(plainText), nil))
return
}