-
Notifications
You must be signed in to change notification settings - Fork 1
/
sign.go
181 lines (150 loc) · 4.89 KB
/
sign.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
package key
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/sha256"
"errors"
"fmt"
"log"
"math/big"
"github.com/scorum/scorum-go/key/rfc6979"
secp256k1 "github.com/btcsuite/btcd/btcec"
)
func SignBufferSha256(bufSha256 []byte, privateKey *ecdsa.PrivateKey) []byte {
var buf_sha256_clone = make([]byte, len(bufSha256))
copy(buf_sha256_clone, bufSha256)
nonce := 0
for {
r, s, err := rfc6979.SignECDSA(privateKey, buf_sha256_clone, sha256.New, nonce)
nonce++
if err != nil {
log.Println(err)
return nil
}
ecsignature := &secp256k1.Signature{R: r, S: s}
der := ecsignature.Serialize()
lenR := der[3]
lenS := der[5+lenR]
if lenR == 32 && lenS == 32 {
// bitcoind checks the bit length of R and S here. The ecdsa signature
// algorithm returns R and S mod N therefore they will be the bitsize of
// the curve, and thus correctly sized.
key := (*secp256k1.PrivateKey)(privateKey)
curve := secp256k1.S256()
max_counter := 4 //max_counter := (curve.H+1)*2
for i := 0; i < max_counter; i++ {
//for i := 0; i < (curve.H+1)*2; i++ {
//for i := 0; ;i++ {
pk, err := recoverKeyFromSignature(curve, ecsignature, buf_sha256_clone, i, true)
if err == nil && pk.X.Cmp(key.X) == 0 && pk.Y.Cmp(key.Y) == 0 {
//result := make([]byte, 1, 2*curve.byteSize+1)
byteSize := curve.BitSize / 8
result := make([]byte, 1, 2*byteSize+1)
result[0] = 27 + byte(i)
if true { // isCompressedKey
result[0] += 4
}
// Not sure this needs rounding but safer to do so.
curvelen := (curve.BitSize + 7) / 8
// Pad R and S to curvelen if needed.
bytelen := (ecsignature.R.BitLen() + 7) / 8
if bytelen < curvelen {
result = append(result, make([]byte, curvelen-bytelen)...)
}
result = append(result, ecsignature.R.Bytes()...)
bytelen = (ecsignature.S.BitLen() + 7) / 8
if bytelen < curvelen {
result = append(result, make([]byte, curvelen-bytelen)...)
}
result = append(result, ecsignature.S.Bytes()...)
return result
}
}
}
}
}
func recoverKeyFromSignature(curve *secp256k1.KoblitzCurve, sig *secp256k1.Signature, msg []byte, iter int, doChecks bool) (*secp256k1.PublicKey, error) {
// 1.1 x = (n * i) + r
Rx := new(big.Int).Mul(curve.Params().N,
new(big.Int).SetInt64(int64(iter/2)))
Rx.Add(Rx, sig.R)
if Rx.Cmp(curve.Params().P) != -1 {
return nil, errors.New("calculated Rx is larger than curve P")
}
// convert 02<Rx> to point R. (step 1.2 and 1.3). If we are on an odd
// iteration then 1.6 will be done with -R, so we calculate the other
// term when uncompressing the point.
Ry, err := decompressPoint(curve, Rx, iter%2 == 1)
if err != nil {
return nil, err
}
// 1.4 Check n*R is point at infinity
if doChecks {
nRx, nRy := curve.ScalarMult(Rx, Ry, curve.Params().N.Bytes())
if nRx.Sign() != 0 || nRy.Sign() != 0 {
return nil, errors.New("n*R does not equal the point at infinity")
}
}
// 1.5 calculate e from message using the same algorithm as ecdsa
// signature calculation.
e := hashToInt(msg, curve)
// Step 1.6.1:
// We calculate the two terms sR and eG separately multiplied by the
// inverse of r (from the signature). We then add them to calculate
// Q = r^-1(sR-eG)
invr := new(big.Int).ModInverse(sig.R, curve.Params().N)
// first term.
invrS := new(big.Int).Mul(invr, sig.S)
invrS.Mod(invrS, curve.Params().N)
sRx, sRy := curve.ScalarMult(Rx, Ry, invrS.Bytes())
// second term.
e.Neg(e)
e.Mod(e, curve.Params().N)
e.Mul(e, invr)
e.Mod(e, curve.Params().N)
minuseGx, minuseGy := curve.ScalarBaseMult(e.Bytes())
// TODO: this would be faster if we did a mult and add in one
// step to prevent the jacobian conversion back and forth.
Qx, Qy := curve.Add(sRx, sRy, minuseGx, minuseGy)
return &secp256k1.PublicKey{
Curve: curve,
X: Qx,
Y: Qy,
}, nil
}
func decompressPoint(curve *secp256k1.KoblitzCurve, x *big.Int, ybit bool) (*big.Int, error) {
// TODO: This will probably only work for secp256k1 due to
// optimizations.
// Y = +-sqrt(x^3 + B)
x3 := new(big.Int).Mul(x, x)
x3.Mul(x3, x)
x3.Add(x3, curve.Params().B)
// now calculate sqrt mod p of x2 + B
// This code used to do a full sqrt based on tonelli/shanks,
// but this was replaced by the algorithms referenced in
// https://bitcointalk.org/index.php?topic=162805.msg1712294#msg1712294
y := new(big.Int).Exp(x3, curve.QPlus1Div4(), curve.Params().P)
if ybit != isOdd(y) {
y.Sub(curve.Params().P, y)
}
if ybit != isOdd(y) {
return nil, fmt.Errorf("ybit doesn't match oddness")
}
return y, nil
}
func isOdd(a *big.Int) bool {
return a.Bit(0) == 1
}
func hashToInt(hash []byte, c elliptic.Curve) *big.Int {
orderBits := c.Params().N.BitLen()
orderBytes := (orderBits + 7) / 8
if len(hash) > orderBytes {
hash = hash[:orderBytes]
}
ret := new(big.Int).SetBytes(hash)
excess := len(hash)*8 - orderBits
if excess > 0 {
ret.Rsh(ret, uint(excess))
}
return ret
}