-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcrypter.go
73 lines (60 loc) · 1.53 KB
/
crypter.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
73
package linkpearl
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"errors"
"io"
)
// Crypter is special object that handles data encryption and decryption
// apart from Matrix' standard encryption.
// It can encrypt and decrypt arbitrary data using secret key (password)
type Crypter struct {
cipher cipher.AEAD
nonceSize int
}
// ErrInvalidData returned in provided encrypted data (ciphertext) is invalid
var ErrInvalidData = errors.New("invalid data")
// NewCrypter creates new Crypter
func NewCrypter(secretkey string) (*Crypter, error) {
block, err := aes.NewCipher([]byte(secretkey))
if err != nil {
return nil, err
}
aesGCM, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
return &Crypter{
cipher: aesGCM,
nonceSize: aesGCM.NonceSize(),
}, nil
}
// Decrypt data
func (c *Crypter) Decrypt(data string) (string, error) {
datab, err := base64.StdEncoding.DecodeString(data)
if err != nil {
return data, err
}
if len(datab) < c.nonceSize {
return data, ErrInvalidData
}
nonce := datab[:c.nonceSize]
ciphertext := datab[c.nonceSize:]
plaintext, err := c.cipher.Open(nil, nonce, ciphertext, nil)
if err != nil {
return data, err
}
return string(plaintext), nil
}
// Encrypt data
func (c *Crypter) Encrypt(data string) (string, error) {
nonce := make([]byte, c.nonceSize)
_, err := io.ReadFull(rand.Reader, nonce)
if err != nil {
return data, err
}
encrypted := c.cipher.Seal(nonce, nonce, []byte(data), nil)
return base64.StdEncoding.EncodeToString(encrypted), nil
}