crypto.go 1.31 KB
Newer Older
vicotor's avatar
vicotor committed
1 2 3 4 5 6
package utils

import (
	"crypto/ecdsa"
	"encoding/hex"
	"github.com/ethereum/go-ethereum/crypto"
vicotor's avatar
vicotor committed
7
	"strings"
vicotor's avatar
vicotor committed
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
)

func HexToPrivatekey(key string) (*ecdsa.PrivateKey, error) {
	return crypto.HexToECDSA(key)
}

func PrivatekeyToHex(key *ecdsa.PrivateKey) string {
	return hex.EncodeToString(crypto.FromECDSA(key))
}

func PrivatekeyToAddress(key *ecdsa.PrivateKey) string {
	return crypto.PubkeyToAddress(key.PublicKey).String()
}

func PubkeyToAddress(key *ecdsa.PublicKey) string {
	return crypto.PubkeyToAddress(*key).String()
}

func PubkeyToHex(key *ecdsa.PublicKey) string {
	pub := crypto.FromECDSAPub(key)
	return hex.EncodeToString(pub)
}

func HexToPubkey(key string) (*ecdsa.PublicKey, error) {
vicotor's avatar
vicotor committed
32 33 34
	if strings.HasPrefix(key, "0x") {
		key = key[2:]
	}
vicotor's avatar
vicotor committed
35 36 37 38
	pub, err := hex.DecodeString(key)
	if err != nil {
		return nil, err
	}
39 40 41
	if len(pub) > 65 {
		pub = pub[:65]
	}
vicotor's avatar
vicotor committed
42 43
	return crypto.UnmarshalPubkey(pub)
}
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61

func VerifySignature(data []byte, signature []byte, oripubkey []byte) bool {
	dataHash := crypto.Keccak256Hash(data)
	if len(signature) == 65 {
		signature = signature[:64]
	}
	pubLen := len(oripubkey)
	pubkey := []byte{}

	if pubLen == 130 || pubLen == 132 {
		pubkey = FromHex(string(oripubkey))
	} else if pubLen == 65 {
		pubkey = oripubkey
	}
	verified := crypto.VerifySignature(pubkey, dataHash[:], signature)

	return verified
}