-
Notifications
You must be signed in to change notification settings - Fork 0
/
key.go
86 lines (74 loc) · 1.75 KB
/
key.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
74
75
76
77
78
79
80
81
82
83
84
85
86
package geheim
import (
"io"
"golang.org/x/crypto/argon2"
"golang.org/x/crypto/hkdf"
"golang.org/x/crypto/scrypt"
)
type KDF int
const (
HKDF KDF = 1 + iota
Argon2id
Scrypt
)
var KDFNames = map[KDF]string{
HKDF: "HKDF",
Argon2id: "Argon2id",
Scrypt: "Scrypt",
}
var saltSizes = map[KDF]int{
HKDF: 32,
Argon2id: 32,
Scrypt: 32,
}
var kdfs = [...]KDF{
HKDF,
Argon2id,
Scrypt,
}
var KDFString = getOptionString(kdfs[:], KDFNames)
const (
MinSec = 0
MaxSec = 20
)
func GetMemory(sec int) int64 { return 1 << (20 + sec) }
func deriveKey(kdf KDF, sec, size int, key, salt []byte) ([]byte, error) {
if sec < MinSec || sec > MaxSec {
return nil, ErrSec
}
memory := GetMemory(sec)
switch kdf {
case Argon2id:
return argon2.IDKey(key, salt, 1, uint32(memory/1024), 128, uint32(size)), nil
case Scrypt:
const r, p = 8, 1
key, err := scrypt.Key(key, salt, int(memory/128/r/p), r, p, size)
return key, err
}
return nil, ErrKDF
}
func deriveKeys(kdf KDF, mdfn MDFunc, sec, sizeCipher, sizeMAC int, key, salt []byte) ([]byte, []byte, error) {
if len(key) == 0 {
return nil, nil, ErrKey
}
if err := checkBytesSize(saltSizes, kdf, salt, "salt"); err != nil {
return nil, nil, err
}
switch kdf {
case HKDF:
keyCipher := make([]byte, sizeCipher)
if _, err := io.ReadFull(hkdf.New(mdfn, key, salt, []byte("CIP")), keyCipher); err != nil {
return nil, nil, err
}
keyMAC := make([]byte, sizeMAC)
if _, err := io.ReadFull(hkdf.New(mdfn, key, salt, []byte("MAC")), keyMAC); err != nil {
return nil, nil, err
}
return keyCipher, keyMAC, nil
}
keys, err := deriveKey(kdf, sec, sizeCipher+sizeMAC, key, salt)
if err != nil {
return nil, nil, err
}
return keys[:sizeCipher], keys[sizeCipher : sizeCipher+sizeMAC], nil
}