/
criptor.go
72 lines (54 loc) · 1.38 KB
/
criptor.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
//
// Implements functions of encription and decription
//
// @author: Rafael Campos Nunes <rafaelnunes@engineer.com>
//
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"fmt"
"io"
)
// Encrypt a given data with a secret
func Encrypt(data []byte, secret string) []byte {
block, err := aes.NewCipher(MD5(secret))
if err != nil {
msg := fmt.Sprintf("Couldn't create a block. Reason %v ", err)
panic(msg)
}
gcm, err := cipher.NewGCM(block)
if err != nil {
msg := fmt.Sprintf("Couldn't create a chiper block. Reason %v ",
err.Error())
panic(msg)
}
nonce := make([]byte, gcm.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
panic(err.Error())
}
encrypted := gcm.Seal(nonce, nonce, data, nil)
return encrypted
}
// Decrypt data with a given secret
func Decrypt(data []byte, secret string) []byte {
block, err := aes.NewCipher(MD5(secret))
if err != nil {
msg := fmt.Sprintf("Couldn't create a block. Reason %v", err)
panic(msg)
}
gcm, err := cipher.NewGCM(block)
if err != nil {
msg := fmt.Sprintf("Couldn't create a wrapper for the block cipher. "+
"Reason %v", err)
panic(msg)
}
nonceSize := gcm.NonceSize()
nonce, cipher := data[:nonceSize], data[nonceSize:]
decrypted, err := gcm.Open(nil, nonce, cipher, nil)
if err != nil {
panic(fmt.Sprintf("Couldn't decrypt message. Reason %v", err))
}
return decrypted
}