decrypt.go 746 Bytes
Newer Older
1
package server
ale's avatar
ale committed
2
3

import (
ale's avatar
ale committed
4
5
	"errors"

ale's avatar
ale committed
6
7
8
9
	"github.com/miscreant/miscreant/go"
	"golang.org/x/crypto/scrypt"
)

ale's avatar
ale committed
10
11
12
13
14
15
16
17
const (
	scryptN = 32768
	scryptR = 8
	scryptP = 1
	keyLen  = 64
	saltLen = 32
)

ale's avatar
ale committed
18
func decrypt(data, pw []byte) ([]byte, error) {
ale's avatar
ale committed
19
20
21
22
23
24
25
	// The KDF salt is prepended to the encrypted key.
	if len(data) < saltLen {
		return nil, errors.New("short data")
	}
	salt := data[:saltLen]
	data = data[saltLen:]

ale's avatar
ale committed
26
27
	// Apply the key derivation function to the password to obtain
	// a 64 byte key.
ale's avatar
ale committed
28
	dk, err := scrypt.Key(pw, salt, scryptN, scryptR, scryptP, keySize)
ale's avatar
ale committed
29
30
31
32
33
34
35
36
37
38
39
40
	if err != nil {
		return nil, err
	}

	// Set up the AES-SIV secret box.
	cipher, err := miscreant.NewAESCMACSIV(dk)
	if err != nil {
		return nil, err
	}

	return cipher.Open(nil, data)
}