-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauthenticatedBlockCipher.go
More file actions
63 lines (56 loc) · 1.41 KB
/
Copy pathauthenticatedBlockCipher.go
File metadata and controls
63 lines (56 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
63
package blockEncryption
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"io"
"io/ioutil"
)
type AuthenticatedBlockCipher struct {
key []byte
}
func NewAuthenticatedBlockCipher(secret []byte) *AuthenticatedBlockCipher {
return &AuthenticatedBlockCipher{key: secret}
}
func (ae *AuthenticatedBlockCipher) EncryptFile(fileName string) ([]byte, error){
//read the file as cyphertext
plainText, err := ioutil.ReadFile(fileName)
if err != nil {
return nil, err
}
return ae.EncryptMessage(plainText)
}
func (ae *AuthenticatedBlockCipher) EncryptMessage(message []byte) ([]byte, error) {
//create new aes cypher
block, err := aes.NewCipher(ae.key)
if err != nil {
return nil, err
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
nonce := make([]byte, aesgcm.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
panic(err.Error())
}
ciphertext := aesgcm.Seal(nonce, nonce, message, nil)
return ciphertext, nil
}
func (ae *AuthenticatedBlockCipher) Decrypt(cipherText []byte) ([]byte, error){
block, err := aes.NewCipher(ae.key)
if err != nil {
return nil, err
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
nonceSize := aesgcm.NonceSize()
nonce, cipherText := cipherText[:nonceSize], cipherText[nonceSize:]
plaintext, err := aesgcm.Open(nil, nonce, cipherText, nil)
if err != nil {
return nil, err
}
return plaintext, nil
}