28

如何解密keystore文件

 5 years ago
source link: https://huoding.com/2018/09/26/697?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

如果你用 geth 创建过账号「geth –datadir /path/to/data account new」,那么多半知道 keystore 文件,它通过一个 password 加密保存着账号的私钥:

rmqe6bR.png!web

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,
    )
}

代码极其简单,就不用多做解释了,收工!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK