go语言从keystore获取私钥和地址

现在要注意geth的版本问题

package main

import (
	"encoding/hex"
	"fmt"
	"github.com/ethereum/go-ethereum/accounts/keystore"
	"io"
	"strings"
)

//根据keystore文件和密码 获取私钥和地址
func getAuth(keystorefileContent, password string) (string, string, error) {
	keyin := strings.NewReader(keystorefileContent)
	json, err := io.ReadAll(keyin)
	if err != nil {
		return "", "", err
	}
	key, err := keystore.DecryptKey(json, password)
	if err != nil {
		return "", "", err
	}
	priKey := key.PrivateKey
	addr := key.Address
	return hex.EncodeToString(priKey.D.Bytes()), addr.Hex(), nil
}

func main() {
	//keyinfo就是keystore文件的内容
	keyinfo := `{"address":"470455a4b2492d75f19ec7b29d25e19aee0c48b1","crypto":{"cipher":"aes-128-ctr","ciphertext":"08ef3a09df1d731bf71d8ce52a0fed4d4c9187f7a5ef845833bac9854700cd70","cipherparams":{"iv":"e8b8b6ed222f8906b31e391e6ef8b7d7"},"kdf":"scrypt","kdfparams":{"dklen":32,"n":262144,"p":1,"r":8,"salt":"e0970e0f38759ee32152429f692df30c0b4efd1d8adef6a9cf2a58e4f67fdcc7"},"mac":"0bea42bc7c1284307f518f4939f2de3af2278ac83e329541bf9e258e107c2feb"},"id":"83cb1145-c55b-439f-a1f0-5416a3805beb","version":3}`
	privateKey, address, err := getAuth(keyinfo, "123456")
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(privateKey, address)
}

你可能感兴趣的:(golang,区块链)