forked from onflow/crypto
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsign.go
More file actions
254 lines (229 loc) · 9.46 KB
/
sign.go
File metadata and controls
254 lines (229 loc) · 9.46 KB
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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
/*
* Flow Crypto
*
* Copyright Flow Foundation.
*
* 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 crypto
import (
"crypto/elliptic"
"fmt"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/onflow/crypto/hash"
)
// revive:disable:var-naming
// revive:enable
// SigningAlgorithm is an identifier for a signing algorithm
// (and parameters if applicable)
type SigningAlgorithm int
const (
// Supported signing algorithms
UnknownSigningAlgorithm SigningAlgorithm = iota
// BLSBLS12381 is BLS on BLS 12-381 curve
BLSBLS12381
// ECDSAP256 is ECDSA on NIST P-256 curve
ECDSAP256
// ECDSASecp256k1 is ECDSA on secp256k1 curve
ECDSASecp256k1
)
// String returns the string representation of this signing algorithm.
func (f SigningAlgorithm) String() string {
return [...]string{"UNKNOWN", "BLS_BLS12381", "ECDSA_P256", "ECDSA_secp256k1"}[f]
}
// Signature is a generic type, regardless of the signature scheme
type Signature []byte
// Signer interface
type signer interface {
// generatePrivateKey generates a private key
generatePrivateKey([]byte) (PrivateKey, error)
// decodePrivateKey loads a private key from a byte array
decodePrivateKey([]byte) (PrivateKey, error)
// decodePublicKey loads a public key from a byte array
decodePublicKey([]byte) (PublicKey, error)
// decodePublicKeyCompressed loads a public key from a byte array representing a point in compressed form
decodePublicKeyCompressed([]byte) (PublicKey, error)
}
// newSigner returns a signer instance
func newSigner(algo SigningAlgorithm) (signer, error) {
switch algo {
case ECDSAP256:
return p256Instance, nil
case ECDSASecp256k1:
return secp256k1Instance, nil
case BLSBLS12381:
return blsInstance, nil
default:
return nil, invalidInputsErrorf("the signature scheme %s is not supported", algo)
}
}
// Initialize the context of all algos
func init() {
// ECDSA
p256Instance = &(ecdsaAlgo{
curve: elliptic.P256(),
algo: ECDSAP256,
})
secp256k1Instance = &(ecdsaAlgo{
curve: btcec.S256(),
algo: ECDSASecp256k1,
})
// BLS
initBLS12381()
blsInstance = &blsBLS12381Algo{
algo: BLSBLS12381,
}
}
// SignatureFormatCheck verifies the format of a serialized signature,
// regardless of messages or public keys.
//
// This function is only defined for ECDSA algos for now.
//
// If SignatureFormatCheck returns false then the input is not a valid
// signature and will fail a verification against any message and public key.
func SignatureFormatCheck(algo SigningAlgorithm, s Signature) (bool, error) {
switch algo {
case ECDSAP256:
return p256Instance.signatureFormatCheck(s), nil
case ECDSASecp256k1:
return secp256k1Instance.signatureFormatCheck(s), nil
default:
return false, invalidInputsErrorf(
"the signature scheme %s is not supported",
algo)
}
}
// GeneratePrivateKey generates a private key of the algorithm using the entropy of the given seed.
//
// The seed minimum length is 32 bytes and it should have enough entropy.
// It is recommended to use a secure crypto RNG to generate the seed.
//
// The function returns:
// - (false, invalidInputsErrors) if the signing algorithm is not supported or
// if the seed length is not valid (less than 32 bytes or larger than 256 bytes)
// - (false, error) if an unexpected error occurs
// - (sk, nil) if key generation was successful
func GeneratePrivateKey(algo SigningAlgorithm, seed []byte) (PrivateKey, error) {
signer, err := newSigner(algo)
if err != nil {
return nil, fmt.Errorf("key generation failed: %w", err)
}
return signer.generatePrivateKey(seed)
}
// DecodePrivateKey decodes an array of bytes into a private key of the given algorithm
//
// The function returns:
// - (nil, invalidInputsErrors) if the signing algorithm is not supported
// - (nil, invalidInputsErrors) if the input does not serialize a valid private key:
// -- ECDSA: a valid input is bytes(x) where bytes() is the big-endian encoding padded to the curve order size (32 bytes),
// and `x` is a scalar strictly smaller than the curve order and strictly larger than zero.
// -- BLS: a valid input is bytes(x) where bytes() is the big-endian encoding padded to the order size of BLS12-381 (32 bytes),
// and `x` is a scalar strictly smaller than the curve order and strictly larger than zero.
// - (nil, error) if an unexpected error occurs
// - (sk, nil) otherwise
func DecodePrivateKey(algo SigningAlgorithm, input []byte) (PrivateKey, error) {
signer, err := newSigner(algo)
if err != nil {
return nil, fmt.Errorf("decode private key failed: %w", err)
}
return signer.decodePrivateKey(input)
}
// DecodePublicKey decodes an array of bytes into a public key of the given algorithm
//
// The function returns:
// - (nil, invalidInputsErrors) if the signing algorithm is not supported
// - (nil, invalidInputsErrors) if the input does not serialize a valid public key:
// -- ECDSA: a valid input is `bytes(x) || bytes(y)` where `bytes()` is the big-endian encoding padded to the field size (32 bytes),
// x and y are a point coordinates reduced modulo the field's prime, with the point being on curve.
// Note that infinity point serialization isn't defined in this package, so an infinity public key cannot be constructed.
// -- BLS: a valid input is a compressed serialization of a G2 point following
// https://www.ietf.org/archive/id/draft-irtf-cfrg-pairing-friendly-curves-08.html#name-zcash-serialization-format-
// Note that infinity point is a valid serialized public key.
// - (nil, error) if an unexpected error occurs
// - (pk, nil) otherwise
func DecodePublicKey(algo SigningAlgorithm, input []byte) (PublicKey, error) {
signer, err := newSigner(algo)
if err != nil {
return nil, fmt.Errorf("decode public key failed: %w", err)
}
return signer.decodePublicKey(input)
}
// DecodePublicKeyCompressed decodes an array of bytes given in a compressed representation into a public key of the given algorithm.
// Only ECDSA is supported (BLS uses the compressed serialization by default).
//
// The function returns:
// - (nil, invalidInputsErrors) if the signing algorithm is not supported (is not ECDSA)
// - (nil, invalidInputsErrors) if the input does not serialize a valid public key:
// -- ECDSA: a valid input is `sign_byte || bytes(x)` according to X9.62 section 4.3.6.
// x is the first point coordinate (reduced modulo the field's prime) of a point being on curve.
// Note that infinity point serialization isn't defined in this package, so an infinity public key cannot be constructed.
// Note that infinity point serialization isn't defined in this package.
// - (nil, error) if an unexpected error occurs
// - (pk, nil) otherwise
func DecodePublicKeyCompressed(algo SigningAlgorithm, data []byte) (PublicKey, error) {
signer, err := newSigner(algo)
if err != nil {
return nil, fmt.Errorf("decode compressed public key failed: %w", err)
}
return signer.decodePublicKeyCompressed(data)
}
// Signature type tools
// Bytes returns a byte array of the signature data
func (s Signature) Bytes() []byte {
return s[:]
}
// String returns a String representation of the signature data
func (s Signature) String() string {
return fmt.Sprintf("%#x", s.Bytes())
}
// Key Pair
// PrivateKey is an unspecified signature scheme private key
type PrivateKey interface {
// Algorithm returns the signing algorithm related to the private key.
Algorithm() SigningAlgorithm
// Size return the key size in bytes.
Size() int
// String return a hex representation of the key
String() string
// Sign generates a signature using the provided hasher.
Sign([]byte, hash.Hasher) (Signature, error)
// PublicKey returns the public key.
PublicKey() PublicKey
// Encode returns a bytes representation of the private key
Encode() []byte
// Equals returns true if the given PrivateKeys are equal. Keys are considered unequal if their algorithms are
// unequal or if their encoded representations are unequal. If the encoding of either key fails, they are considered
// unequal as well.
Equals(PrivateKey) bool
}
// PublicKey is an unspecified signature scheme public key.
type PublicKey interface {
// Algorithm returns the signing algorithm related to the public key.
Algorithm() SigningAlgorithm
// Size() return the key size in bytes.
Size() int
// String return a hex representation of the key
String() string
// Verify verifies a signature of an input message using the provided hasher.
Verify(Signature, []byte, hash.Hasher) (bool, error)
// Encode returns a bytes representation of the public key.
Encode() []byte
// EncodeCompressed returns a compressed byte representation of the public key.
// The compressed serialization concept is generic to elliptic curves,
// but we refer to individual curve parameters for details of the compressed format
EncodeCompressed() []byte
// Equals returns true if the given PublicKeys are equal. Keys are considered unequal if their algorithms are
// unequal or if their encoded representations are unequal. If the encoding of either key fails, they are considered
// unequal as well.
Equals(PublicKey) bool
}