/
crypt.go
53 lines (40 loc) · 1.14 KB
/
crypt.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
// Created on: 2022-02-20
package gnotes
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"fmt"
"io"
)
func (c *S3Config) Encrypt(data []byte) ([]byte, error) {
if c.CryptKey == "" {
return []byte{}, fmt.Errorf("need a 16 bit key")
}
block, err := aes.NewCipher([]byte(c.CryptKey))
if err != nil {
return []byte{}, fmt.Errorf("could not create new cipher: %s", err)
}
encData := make([]byte, aes.BlockSize+len(data))
iv := encData[:aes.BlockSize]
if _, err = io.ReadFull(rand.Reader, iv); err != nil {
return []byte{}, fmt.Errorf("could not encrypt: %s", err)
}
stream := cipher.NewCFBEncrypter(block, iv)
stream.XORKeyStream(encData[aes.BlockSize:], data)
return encData, nil
}
func (c *S3Config) Decrypt(data []byte) ([]byte, error) {
block, err := aes.NewCipher([]byte(c.CryptKey))
if err != nil {
return []byte{}, fmt.Errorf("could not create new cipher: %s", err)
}
if len(data) < aes.BlockSize {
return []byte{}, fmt.Errorf("invalid ciphertext block size")
}
iv := data[:aes.BlockSize]
data = data[aes.BlockSize:]
stream := cipher.NewCFBDecrypter(block, iv)
stream.XORKeyStream(data, data)
return data, nil
}