-
Notifications
You must be signed in to change notification settings - Fork 1
/
kdf.go
72 lines (66 loc) · 1.32 KB
/
kdf.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
package main
import (
"github.com/anyproto/go-slip10"
"github.com/tmthrgd/go-memset"
"github.com/tyler-smith/go-bip32"
)
const (
KindEd25519 = iota
KindSecp256k1
)
type Key struct {
Kind uint8
Public []byte
Private []byte
}
func DeriveKey(path []HdIndex, curve string, seed []byte) *Key {
switch curve {
case "ed25519":
return deriveKeyEd25519(path, seed)
case "secp256k1":
return deriveKeySecp256k1(path, seed)
default:
panic("invalid curve: " + curve)
}
}
func deriveKeyEd25519(path []HdIndex, seed []byte) *Key {
node, err := slip10.NewMasterNode(seed)
if err != nil {
panic(err)
}
for i := 0; i < len(path); i++ {
var newNode slip10.Node
newNode, err = node.Derive(path[i])
memset.Memset(node.RawSeed(), 0)
if err != nil {
panic(err)
}
node = newNode
}
pub, sec := node.Keypair()
return &Key{
Kind: KindEd25519,
Public: []byte(pub),
Private: sec.Seed(),
}
}
func deriveKeySecp256k1(path []HdIndex, seed []byte) *Key {
node, err := bip32.NewMasterKey(seed)
if err != nil {
panic(err)
}
for i := 0; i < len(path); i++ {
var newNode *bip32.Key
newNode, err = node.NewChildKey(path[i])
memset.Memset(node.Key, 0)
if err != nil {
panic(err)
}
node = newNode
}
return &Key{
Kind: KindSecp256k1,
Public: node.PublicKey().Key,
Private: node.Key[1:],
}
}