-
Notifications
You must be signed in to change notification settings - Fork 246
/
crypto.go
81 lines (65 loc) · 1.76 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
package crypto
import (
"crypto/ecdsa"
"encoding/hex"
"errors"
"fmt"
"github.com/ethereum/go-ethereum/crypto"
)
// Sign signs the hash of an arbitrary string
func Sign(content string, identity *ecdsa.PrivateKey) (string, error) {
signature, err := crypto.Sign(crypto.Keccak256([]byte(content)), identity)
if err != nil {
return "", err
}
return hex.EncodeToString(signature), nil
}
// VerifySignatures verifys tuples of signatures content/hash/public key
func VerifySignatures(signaturePairs [][3]string) error {
for _, signaturePair := range signaturePairs {
content := crypto.Keccak256([]byte(signaturePair[0]))
signature, err := hex.DecodeString(signaturePair[1])
if err != nil {
return err
}
publicKeyBytes, err := hex.DecodeString(signaturePair[2])
if err != nil {
return err
}
publicKey, err := crypto.UnmarshalPubkey(publicKeyBytes)
if err != nil {
return err
}
recoveredKey, err := crypto.SigToPub(
content,
signature,
)
if err != nil {
return err
}
if crypto.PubkeyToAddress(*recoveredKey) != crypto.PubkeyToAddress(*publicKey) {
return errors.New("identity key and signature mismatch")
}
}
return nil
}
// ExtractSignatures extract from tuples of signatures content a public key
func ExtractSignatures(signaturePairs [][2]string) ([]string, error) {
response := make([]string, len(signaturePairs))
for i, signaturePair := range signaturePairs {
content := crypto.Keccak256([]byte(signaturePair[0]))
signature, err := hex.DecodeString(signaturePair[1])
if err != nil {
return nil, err
}
recoveredKey, err := crypto.SigToPub(
content,
signature,
)
if err != nil {
return nil, err
}
response[i] = fmt.Sprintf("%x", crypto.FromECDSAPub(recoveredKey))
}
return response, nil
}