aboutsummaryrefslogtreecommitdiff
path: root/backend/security/encrypt.go
blob: 4af5e3ccefba61b552297c13f27b5927265dbecc (plain) (blame)
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
74
75
76
77
78
79
80
81
package security

import (
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
	"errors"
	"golang.org/x/crypto/scrypt"
)

var EncryptionError = errors.New("could not encrypt the given content")

func Encrypt(key, data string) (string, error) {
	// initialize aes block cipher with given key
	blockCipher, err := aes.NewCipher([]byte(key))
	if err != nil {
		return "", err
	}

	// wrap block cipher with Galois Counter Mode and standard nonce length
	gcm, err := cipher.NewGCM(blockCipher)
	if err != nil {
		return "", err
	}

	// generate nonce (number once used) unique to the given key
	nonce := make([]byte, gcm.NonceSize())
	if _, err = rand.Read(nonce); err != nil {
		return "", err
	}

	// seal nonce with data to use during decryption
	cipherText := gcm.Seal(nonce, nonce, []byte(data), nil)

	return string(cipherText), nil
}

func Decrypt(key, data string) (string, error) {
	// similar to encrypt, create cipher and wrap with GCM
	blockCipher, err := aes.NewCipher([]byte(key))
	if err != nil {
		return "", err
	}

	gcm, err := cipher.NewGCM(blockCipher)
	if err != nil {
		return "", err
	}

	// extract the nonce from the data
	nonce, cipherText := data[:gcm.NonceSize()], data[gcm.NonceSize():]

	// use nonce to decrypt the data
	plaintext, err := gcm.Open(nil, []byte(nonce), []byte(cipherText), nil)
	if err != nil {
		return "", err
	}

	return string(plaintext), nil
}

const keyBytes = 16
const iterations = 16384
const relativeMemoryCost = 8
const relativeCPUCost = 1

func DeriveKey(password string, salt []byte) (string, []byte, error) {
	if salt == nil {
		salt = make([]byte, keyBytes)
		if _, err := rand.Read(salt); err != nil {
			return "", nil, err
		}
	}

	key, err := scrypt.Key([]byte(password), salt, iterations, relativeMemoryCost, relativeCPUCost, keyBytes)
	if err != nil {
		return "", nil, err
	}

	return string(key), salt, nil
}