-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkeypair.go
76 lines (59 loc) · 1.64 KB
/
keypair.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
package crypto
import (
"crypto/subtle"
"golang.org/x/crypto/argon2"
)
type Algorithm struct {
Type AlgorithmType
Parameters map[string]int
}
type AlgorithmType int
const (
Argon2 AlgorithmType = iota
Bcrypt
)
type AccessType int
const (
RootKey AccessType = iota
SessionKey
)
type Keypair struct {
Type AccessType
Algorithm Algorithm
Salt []byte
PrivateKey []byte
PublicKey []byte
Hash []byte // Sometimes called Address, also provides merkle hash data
RootKey *Keypair
ParentKey *Keypair
ChildKeys []*Keypair
}
func (self Keypair) Params(name string) int {
return self.Algorithm.Parameters[name]
}
func (self Keypair) GeneratePublicKey() []byte {
switch self.Algorithm.Type {
case Argon2:
return argon2.IDKey(self.PrivateKey, self.Salt, self.Params("iterations"), self.Params("memory"), self.Params("threads"), self.Params("length"))
default:
return []byte{}
}
}
func (self Keypair) IsPrivateKey(seed []byte) (match bool, err error) {
// Extract the parameters, salt and derived key from the encoded password
// hash.
p, salt, hash, err := decodeHash(encodedHash)
if err != nil {
return false, err
}
// Derive the key from the other password using the same parameters.
// Derive the key from the other password using the same parameters.
otherHash := argon2.IDKey(seed, salt, p.iterations, p.memory, p.parallelism, p.keyLength)
// Check that the contents of the hashed passwords are identical. Note
// that we are using the subtle.ConstantTimeCompare() function for this
// to help prevent timing attacks.
if subtle.ConstantTimeCompare(hash, otherHash) == 1 {
return true, nil
}
return false, nil
}