forked from niubaoshu/gotiny
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathencryption.go
More file actions
62 lines (51 loc) · 1.41 KB
/
encryption.go
File metadata and controls
62 lines (51 loc) · 1.41 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
package gotiny
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
)
type aesConfigStruct struct {
block *cipher.Block
gcm cipher.AEAD
nonceSize int
}
func newAESconfig(key []byte) *aesConfigStruct {
block, _ := aes.NewCipher(key)
gcm, _ := cipher.NewGCM(block)
return &aesConfigStruct{
block: &block,
gcm: gcm,
nonceSize: gcm.NonceSize(),
}
}
// create AES-256 config for encryption encoding key must be 32 byte
func NewAES256config(key [32]byte) *aesConfigStruct {
return newAESconfig(key[:])
}
// create AES-192 config for encryption encoding key must be 24 byte
func NewAES192config(key [24]byte) *aesConfigStruct {
return newAESconfig(key[:])
}
// create AES-128 config for encryption encoding key must be 16 byte
func NewAES128config(key [16]byte) *aesConfigStruct {
return newAESconfig(key[:])
}
// Generate a random nonce
func (aesConfig *aesConfigStruct) generatorNonce() []byte {
nonce := make([]byte, aesConfig.nonceSize)
rand.Read(nonce)
return nonce
}
// Encrypt the plaintext
func (aesConfig *aesConfigStruct) Encrypt(plaintext []byte) []byte {
nonce := aesConfig.generatorNonce()
return aesConfig.gcm.Seal(nonce, nonce, plaintext, nil)
}
// Decrypt the cipherData
func (aesConfig *aesConfigStruct) Decrypt(cipherData []byte) []byte {
decrypted, _ := aesConfig.gcm.Open(nil,
cipherData[:aesConfig.nonceSize],
cipherData[aesConfig.nonceSize:],
nil)
return decrypted
}