-
-
Notifications
You must be signed in to change notification settings - Fork 33
/
encryption.go
60 lines (54 loc) · 1.52 KB
/
encryption.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
// modified from
// https://www.thepolyglotdeveloper.com/2018/02/encrypt-decrypt-data-golang-application-crypto-packages/
package portwarden
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/sha256"
"errors"
"io"
"golang.org/x/crypto/pbkdf2"
)
const (
ErrMessageAuthenticationFailed = "cipher: message authentication failed"
ErrWrongBackupPassphrase = "wrong backup passphrase entered"
)
// derive a key from the master password
func DeriveKey(passphrase string) []byte {
return pbkdf2.Key([]byte(passphrase), []byte(Salt), 4096, 32, sha256.New)
}
func EncryptBytes(data []byte, passphrase string) ([]byte, error) {
block, _ := aes.NewCipher(DeriveKey(passphrase))
gcm, err := cipher.NewGCM(block)
if err != nil {
return []byte{}, err
}
nonce := make([]byte, gcm.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
return []byte{}, err
}
ciphertext := gcm.Seal(nonce, nonce, data, nil)
return ciphertext, nil
}
func DecryptBytes(data []byte, passphrase string) ([]byte, error) {
key := DeriveKey(passphrase)
block, err := aes.NewCipher(key)
if err != nil {
return []byte{}, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return []byte{}, err
}
nonceSize := gcm.NonceSize()
nonce, ciphertext := data[:nonceSize], data[nonceSize:]
plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
if err.Error() == ErrMessageAuthenticationFailed {
return []byte{}, errors.New(ErrWrongBackupPassphrase)
}
return []byte{}, err
}
return plaintext, nil
}