-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcrypto.go
187 lines (165 loc) · 5.22 KB
/
crypto.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
// Copyright 2019 - 2023 Weald Technology Trading.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package util
import (
"crypto/sha256"
"fmt"
"math/big"
"strconv"
"strings"
"github.com/pkg/errors"
bytesutil "github.com/wealdtech/go-bytesutil"
e2types "github.com/wealdtech/go-eth2-types/v2"
"golang.org/x/crypto/hkdf"
)
func _bigInt(input string) *big.Int {
result, _ := new(big.Int).SetString(input, 10)
return result
}
//nolint:gochecknoglobals
var r = _bigInt("52435875175126190479447740508185965837690552500527637822603658699938581184513")
// 48 comes from ceil((1.5 * ceil(log2(r))) / 8).
const l = 48
// PrivateKeyFromSeedAndPath generates a private key given a seed and a path.
// Follows ERC-2334.
func PrivateKeyFromSeedAndPath(seed []byte, path string) (*e2types.BLSPrivateKey, error) {
if path == "" {
return nil, errors.New("no path")
}
if len(seed) < 16 {
return nil, errors.New("seed must be at least 128 bits")
}
pathBits := strings.Split(path, "/")
var sk *big.Int
var err error
for i := range pathBits {
switch pathBits[i] {
case "":
return nil, fmt.Errorf("no entry at path component %d", i)
case "m":
if i != 0 {
return nil, fmt.Errorf("invalid master at path component %d", i)
}
sk, err = DeriveMasterSK(seed)
if err != nil {
return nil, errors.Wrapf(err, "failed to generate master key at path component %d", i)
}
default:
if i == 0 {
return nil, fmt.Errorf("not master at path component %d", i)
}
index, err := strconv.ParseUint(pathBits[i], 10, 32)
if err != nil {
return nil, fmt.Errorf("invalid index %q at path component %d", pathBits[i], i)
}
sk, err = DeriveChildSK(sk, uint32(index))
if err != nil {
return nil, errors.Wrapf(err, "failed to derive child SK at path component %d", i)
}
}
}
// SK can be shorter than 32 bytes so left-pad it here.
bytes := make([]byte, 32)
skBytes := sk.Bytes()
copy(bytes[32-len(skBytes):], skBytes)
return e2types.BLSPrivateKeyFromBytes(bytes)
}
// DeriveMasterSK derives the master secret key from a seed.
// Follows ERC-2333.
func DeriveMasterSK(seed []byte) (*big.Int, error) {
if len(seed) < 16 {
return nil, errors.New("seed must be at least 128 bits")
}
return hkdfModR(seed, "")
}
// DeriveChildSK derives the child secret key from a parent key.
// Follows ERC-2333.
func DeriveChildSK(parentSK *big.Int, index uint32) (*big.Int, error) {
pk, err := parentSKToLamportPK(parentSK, index)
if err != nil {
return nil, err
}
return hkdfModR(pk, "")
}
// ikmToLamportSK creates a Lamport secret key.
func ikmToLamportSK(ikm []byte, salt []byte) ([255][32]byte, error) {
prk := hkdf.Extract(sha256.New, ikm, salt)
okm := hkdf.Expand(sha256.New, prk, nil)
var lamportSK [255][32]byte
for i := 0; i < 255; i++ {
var result [32]byte
read, err := okm.Read(result[:])
if err != nil {
return lamportSK, err
}
if read != 32 {
return lamportSK, fmt.Errorf("only read %d bytes", read)
}
lamportSK[i] = result
}
return lamportSK, nil
}
// parentSKToLamportPK generates the Lamport private key from a BLS secret key.
func parentSKToLamportPK(parentSK *big.Int, index uint32) ([]byte, error) {
salt := i2OSP(big.NewInt(int64(index)), 4)
ikm := i2OSP(parentSK, 32)
lamport0, err := ikmToLamportSK(ikm, salt)
if err != nil {
return nil, err
}
notIKM := bytesutil.XOR(ikm)
lamport1, err := ikmToLamportSK(notIKM, salt)
if err != nil {
return nil, err
}
lamportPK := make([]byte, (255+255)*32)
for i := 0; i < 255; i++ {
copy(lamportPK[32*i:], SHA256(lamport0[i][:]))
}
for i := 0; i < 255; i++ {
copy(lamportPK[(i+255)*32:], SHA256(lamport1[i][:]))
}
compressedLamportPK := SHA256(lamportPK)
return compressedLamportPK, nil
}
// hkdfModR hashes 32 random bytes into the subgroup of the BLS12-381 private keys.
func hkdfModR(ikm []byte, keyInfo string) (*big.Int, error) {
salt := []byte("BLS-SIG-KEYGEN-SALT-")
sk := big.NewInt(0)
for sk.Cmp(big.NewInt(0)) == 0 {
salt = SHA256(salt)
prk := hkdf.Extract(sha256.New, append(ikm, i2OSP(big.NewInt(0), 1)...), salt)
okm := hkdf.Expand(sha256.New, prk, append([]byte(keyInfo), i2OSP(big.NewInt(int64(l)), 2)...))
okmOut := make([]byte, l)
read, err := okm.Read(okmOut)
if err != nil {
return nil, err
}
if read != l {
return nil, fmt.Errorf("only read %d bytes", read)
}
sk = new(big.Int).Mod(osToIP(okmOut), r)
}
return sk, nil
}
// osToIP turns a byte array in to an integer as per https://ietf.org/rfc/rfc3447.txt
func osToIP(data []byte) *big.Int {
return new(big.Int).SetBytes(data)
}
// i2OSP turns an integer in to a byte array as per https://ietf.org/rfc/rfc3447.txt
func i2OSP(data *big.Int, resLen int) []byte {
res := make([]byte, resLen)
bytes := data.Bytes()
copy(res[resLen-len(bytes):], bytes)
return res
}