如果你用 geth 创建过账号「geth –datadir /path/to/data account new」,那么多半知道 keystore 文件,它通过一个 password 加密保存着账号的私钥:
keystore
如果我想拿到加密前的私钥怎么办?最容易想到的办法是在 MetaMask 中导入账号的时候选择通过 JSON 文件导入的方式,然后再导出私钥。不过这个方法不方便,也无法实现自动化,下面看看如何通过 golang 解密 keystore 文件:
package main
import (
"encoding/hex"
"flag"
"fmt"
"io/ioutil"
"os"
"github.com/ethereum/go-ethereum/accounts/keystore"
"github.com/ethereum/go-ethereum/crypto"
)
var (
file = flag.String("file", "", "file")
password = flag.String("password", "", "password")
)
func init() {
flag.Parse()
}
func main() {
if _, err := os.Stat(*file); os.IsNotExist(err) {
flag.Usage()
os.Exit(1)
}
keyjson, err := ioutil.ReadFile(*file)
if err != nil {
panic(err)
}
key, err := keystore.DecryptKey(keyjson, *password)
if err != nil {
panic(err)
}
address := key.Address.Hex()
privateKey := hex.EncodeToString(crypto.FromECDSA(key.PrivateKey))
fmt.Printf("Address:\t%s\nPrivateKey:\t%s\n",
address,
privateKey,
)
}
更新:本文仅为演示,不推荐通过 flag 传递密码,否则可以在 history 中看到。