/
crypto.go
67 lines (51 loc) · 1.64 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
package crypto
import (
"crypto/ecdsa"
"errors"
eth "github.com/ethereum/go-ethereum/crypto"
)
func GeneratePrivateKey() (*ecdsa.PrivateKey, error) {
return eth.GenerateKey()
}
func MarshalPrivateKey(privateKey *ecdsa.PrivateKey) []byte {
return eth.FromECDSA(privateKey)
}
func UnmarshalPrivateKey(privateKey []byte) (*ecdsa.PrivateKey, error) {
return eth.ToECDSA(privateKey)
}
func MarshalPublicKey(publicKey *ecdsa.PublicKey) []byte {
return eth.FromECDSAPub(publicKey)
}
func UnmarshalPublicKey(publicKey []byte) (*ecdsa.PublicKey, error) {
return eth.UnmarshalPubkey(publicKey)
}
func PublicKeyFromPrivateKey(privateKey *ecdsa.PrivateKey) (*ecdsa.PublicKey, error) {
publicKey := privateKey.Public()
publicKeyECDSA, ok := publicKey.(*ecdsa.PublicKey)
if !ok {
return nil, errors.New("cannot assert type: publicKey is not of type *ecdsa.PublicKey")
}
return publicKeyECDSA, nil
}
func HashData(data []byte) []byte {
hash := eth.Keccak256Hash(data)
return hash.Bytes()
}
func SignData(data []byte, privateKey []byte) ([]byte, error) {
privateKeyECDSA, err := UnmarshalPrivateKey(privateKey)
if err != nil {
return nil, err
}
return eth.Sign(data, privateKeyECDSA)
}
func PublicKeyFromSignature(data []byte, signature []byte) ([]byte, error) {
return eth.Ecrecover(data, signature)
}
func VerifySignature(data []byte, publicKey []byte, signature []byte) bool {
signatureNoRecoverID := signature[:len(signature)-1] // remove recovery id
return eth.VerifySignature(publicKey, data, signatureNoRecoverID)
}
func AddressFromPublicKey(publicKey *ecdsa.PublicKey) []byte {
address := eth.PubkeyToAddress(*publicKey)
return address.Bytes()
}