-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathutilSignature.go
More file actions
338 lines (286 loc) · 9.55 KB
/
utilSignature.go
File metadata and controls
338 lines (286 loc) · 9.55 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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
// Copyright (c) 2023 gpress Authors.
//
// This file is part of gpress.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package main
import (
"crypto/ed25519"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"math/big"
"strings"
dcrdEcdsa "github.com/decred/dcrd/dcrec/secp256k1/v4/ecdsa"
"golang.org/x/crypto/ripemd160"
"golang.org/x/crypto/sha3"
)
// verifyEthereumSignature 验证 Ethereum secp256k1 的签名
func verifyEthereumSignature(chainAddress string, msg string, signature string) (bool, error) {
signatureBytes, err := fromHex(signature)
if err != nil {
return false, err
}
if len(signatureBytes) < 65 {
return false, errors.New("invalid signature")
}
// 计算消息的哈希,包括 MetaMask 的消息前缀
prefix := fmt.Sprintf("\x19Ethereum Signed Message:\n%d%s", len(msg), msg)
messageHash := keccak256Hash([]byte(prefix))
r, s, v := signatureBytes[:32], signatureBytes[32:64], signatureBytes[64]
sign, err := hex.DecodeString(fmt.Sprintf("%x%x%x", v, r, s))
if err != nil {
return false, err
}
dcrdPublicKey, _, err := dcrdEcdsa.RecoverCompact(sign, messageHash)
if err != nil {
return false, err
}
pubKeyBytes := dcrdPublicKey.SerializeUncompressed()[1:]
addressHash := keccak256Hash(pubKeyBytes)
address := ""
if len(addressHash) > 20 {
address = fmt.Sprintf("0x%x", addressHash[len(addressHash)-20:])
}
return strings.EqualFold(address, chainAddress), nil
}
// verifySolanaSignature 验证 Solana ed25519 的签名
func verifySolanaSignature(chainAddress string, msg string, signature string) (bool, error) {
var signatureBytes []byte
var err error
// 尝试 hex 解码(优先)
signatureBytes, err = fromHex(signature)
if err != nil {
// Solana 使用 base64 编码的签名
signatureBytes, err = base64.StdEncoding.DecodeString(signature)
if err != nil {
return false, errors.New("invalid signature encoding")
}
}
if len(signatureBytes) != 64 {
return false, errors.New("invalid signature length")
}
// 解码地址 (Solana 地址是 base58 编码的 32 字节公钥)
addressBytes := base58Decode(chainAddress)
if len(addressBytes) != 32 {
return false, errors.New("invalid address")
}
// Solana 消息前缀
prefix := fmt.Sprintf("\x19Solana Signed Message:\n%d%s", len(msg), msg)
messageHash := hashUsingSha256([]byte(prefix))
// ed25519 签名验证:直接使用地址作为公钥验证
valid := ed25519.Verify(addressBytes, messageHash, signatureBytes)
return valid, nil
}
// verifyXuperChainSignature XuperChain 使用 NIST/secp256r1 标准的公钥,验证签名
func verifyXuperChainSignature(chainAddress string, msg string, signature string) (valid bool, err error) {
verify, publicKey, err := verifySecp256r1Signature(msg, signature)
if !verify || err != nil {
return false, err
}
// 验证 XuperChain 的 address
verifyAddress, _ := verifyAddressUsingPublicKey(chainAddress, publicKey)
if !verifyAddress {
return false, errors.New(funcT("The public key in the signature does not match the address"))
}
return true, nil
}
// verifySecp256r1Signature 验证 secp256r1 的签名
func verifySecp256r1Signature(msg string, signature string) (bool, *ecdsa.PublicKey, error) {
signatureBytes, err := fromHex(signature)
if err != nil {
return false, nil, err
}
if len(signatureBytes) < 65 {
return false, nil, errors.New("invalid signature")
}
// 计算消息的哈希,包括消息前缀
prefix := fmt.Sprintf("\x86XuperChain Signed Message:\n%d%s", len(msg), msg)
messageHash := keccak256Hash([]byte(prefix))
r := new(big.Int).SetBytes(signatureBytes[:32])
s := new(big.Int).SetBytes(signatureBytes[32:64])
v := signatureBytes[64]
publicKey, err := recoverP256PublicKey(messageHash, r, s, uint(v))
if err != nil {
return false, publicKey, err
}
return true, publicKey, nil
}
// fromHex 将 16 进制字符串解码为字节数组
func fromHex(s string) ([]byte, error) {
if len(s) >= 2 && s[0] == '0' && (s[1] == 'x' || s[1] == 'X') {
s = s[2:]
}
if len(s)%2 == 1 {
s = "0" + s
}
return hex.DecodeString(s)
}
// keccak256Hash 对字节数字进行 hash
func keccak256Hash(data []byte) []byte {
d := sha3.NewLegacyKeccak256()
d.Write(data)
return d.Sum(nil)
}
/*
// checkKeyCurve 判断是否是 NIST 标准的公钥
func checkKeyCurve(k *ecdsa.PublicKey) bool {
if k.X == nil || k.Y == nil {
return false
}
switch k.Params().Name {
case "P-256": // NIST
return true
default: // 不支持的密码学类型
return false
}
}
type ECDSASignature struct {
R, S *big.Int
}
*/
// verifyAddressUsingPublicKey 验证钱包地址是否和指定的公钥匹配。如果成功,返回 true 和对应的密码学标记位;如果失败,返回 false 和默认的密码学标记位 0
func verifyAddressUsingPublicKey(address string, pub *ecdsa.PublicKey) (bool, uint8) {
//base58 反解回 byte[] 数组
slice := base58Decode(address)
//检查是否是合法的 base58 编码
if len(slice) < 1 {
return false, 0
}
//拿到密码学标记位
byteVersion := slice[:1]
nVersion := uint8(byteVersion[0])
realAddress, error := getAddressFromPublicKey(pub)
if error != nil {
return false, 0
}
if realAddress == address {
return true, nVersion
}
return false, 0
}
// getAddressFromPublicKey 返回 33 位长度的 Address
func getAddressFromPublicKey(pub *ecdsa.PublicKey) (string, error) {
// 将 ECDSA 公钥转换为 ECDH 公钥
ecdhPublicKey, err := pub.ECDH()
if err != nil {
return "", err
}
// 替换废弃的 elliptic.Marshal 函数
data := ecdhPublicKey.Bytes()
outputSha256 := hashUsingSha256(data)
OutputRipemd160 := hashUsingRipemd160(outputSha256)
//暂时只支持一个字节长度,也就是 uint8 的密码学标志位
// 判断是否是 nist 标准的私钥
nVersion := 1
switch pub.Params().Name {
case "P-256": // NIST
case "SM2-P-256": // 国密
nVersion = 2
default: // 不支持的密码学类型
return "", fmt.Errorf("this cryptography[%v] has not been supported yet", pub.Params().Name)
}
bufVersion := []byte{byte(nVersion)}
strSlice := make([]byte, len(bufVersion)+len(OutputRipemd160))
copy(strSlice, bufVersion)
copy(strSlice[len(bufVersion):], OutputRipemd160)
//using double SHA256 for future risks
checkCode := doubleSha256(strSlice)
simpleCheckCode := checkCode[:4]
slice := make([]byte, len(strSlice)+len(simpleCheckCode))
copy(slice, strSlice)
copy(slice[len(strSlice):], simpleCheckCode)
//使用 base58 编码,手写不容易出错.
//相比 Base64,Base58 不使用数字"0",字母大写"O",字母大写"I",和字母小写"l",以及"+"和"/"符号
strEnc := base58Encode(slice)
return strEnc, nil
}
// hashUsingSha256 使用 sha256 Hash
func hashUsingSha256(data []byte) []byte {
h := sha256.New()
h.Write(data)
out := h.Sum(nil)
return out
}
// doubleSha256 执行 2 次 SHA256,这是为了防止 SHA256 算法被攻破
func doubleSha256(data []byte) []byte {
return hashUsingSha256(hashUsingSha256(data))
}
// hashUsingRipemd160 Ripemd160 hash 算法可以缩短长度
func hashUsingRipemd160(data []byte) []byte {
h := ripemd160.New()
h.Write(data)
out := h.Sum(nil)
return out
}
// TODO 偶尔会恢复失败,原因待查
// recoverP256PublicKey 根据签名的 r,s,v 恢复 P256 的公钥
func recoverP256PublicKey(hash []byte, r *big.Int, s *big.Int, v uint) (*ecdsa.PublicKey, error) {
curve := elliptic.P256()
params := curve.Params()
//v 和 recoveryID 的奇偶性是相反的
recoveryID := (v + 1) % 2
// 检查 r 和 s 范围
if r.Sign() <= 0 || s.Sign() <= 0 || r.Cmp(params.N) >= 0 || s.Cmp(params.N) >= 0 {
return nil, errors.New("invalid r/s value")
}
// 计算 R 点 x 坐标
x := new(big.Int).Set(r)
if x.Cmp(params.P) >= 0 {
return nil, errors.New("r >= P")
}
// 计算 y² = x³ - 3x + b mod P
x3 := new(big.Int).Exp(x, big.NewInt(3), params.P)
threeX := new(big.Int).Mul(x, big.NewInt(3))
threeX.Mod(threeX, params.P)
ySquared := new(big.Int).Sub(x3, threeX)
ySquared.Add(ySquared, params.B)
ySquared.Mod(ySquared, params.P)
// 计算 y 坐标
y := new(big.Int).ModSqrt(ySquared, params.P)
if y == nil {
return nil, errors.New("invalid R point")
}
// 根据恢复 ID 调整 y 奇偶性
if (y.Bit(0) == 0 && recoveryID == 1) || (y.Bit(0) == 1 && recoveryID == 0) {
y.Sub(params.P, y)
}
// 计算 r 的模逆元
rInv := new(big.Int).ModInverse(r, params.N)
if rInv == nil {
return nil, errors.New("r is not invertible")
}
// 计算 sR 点
sRx, sRy := curve.ScalarMult(x, y, s.Bytes())
// 计算 e = hash mod N
e := new(big.Int).SetBytes(hash)
e.Mod(e, params.N)
// 计算 eG 点
eGx, eGy := curve.ScalarBaseMult(e.Bytes())
// 计算 sR - eG
minusEGy := new(big.Int).Neg(eGy)
minusEGy.Mod(minusEGy, params.P)
sumX, sumY := curve.Add(sRx, sRy, eGx, minusEGy)
// 乘以 r 逆元得到公钥 Q
qX, qY := curve.ScalarMult(sumX, sumY, rInv.Bytes())
// 验证点有效性
if !curve.IsOnCurve(qX, qY) {
return nil, errors.New("recovered point is invalid")
}
return &ecdsa.PublicKey{Curve: curve, X: qX, Y: qY}, nil
}