Skip to content

Commit eeb53bc

Browse files
stevenroosefjl
authored andcommitted
cmd/ethkey: new command line tool for keys (#15438)
ethkey is a new tool that serves as a command line interface to the basic key management functionalities of geth. It currently supports: - generating keyfiles - inspecting keyfiles (print public and private key) - signing messages - verifying signed messages
1 parent e21aa0f commit eeb53bc

6 files changed

Lines changed: 533 additions & 0 deletions

File tree

‎cmd/ethkey/README.md‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
ethkey
2+
======
3+
4+
ethkey is a simple command-line tool for working with Ethereum keyfiles.
5+
6+
7+
# Usage
8+
9+
### `ethkey generate`
10+
11+
Generate a new keyfile.
12+
If you want to use an existing private key to use in the keyfile, it can be
13+
specified by setting `--privatekey` with the location of the file containing the
14+
private key.
15+
16+
17+
### `ethkey inspect <keyfile>`
18+
19+
Print various information about the keyfile.
20+
Private key information can be printed by using the `--private` flag;
21+
make sure to use this feature with great caution!
22+
23+
24+
### `ethkey sign <keyfile> <message/file>`
25+
26+
Sign the message with a keyfile.
27+
It is possible to refer to a file containing the message.
28+
29+
30+
### `ethkey verify <address> <signature> <message/file>`
31+
32+
Verify the signature of the message.
33+
It is possible to refer to a file containing the message.
34+
35+
36+
## Passphrases
37+
38+
For every command that uses a keyfile, you will be prompted to provide the
39+
passphrase for decrypting the keyfile. To avoid this message, it is possible
40+
to pass the passphrase by using the `--passphrase` flag pointing to a file that
41+
contains the passphrase.

‎cmd/ethkey/generate.go‎

Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
package main
2+
3+
import (
4+
"crypto/ecdsa"
5+
"crypto/rand"
6+
"fmt"
7+
"io/ioutil"
8+
"os"
9+
"path/filepath"
10+
11+
"github.com/ethereum/go-ethereum/accounts/keystore"
12+
"github.com/ethereum/go-ethereum/cmd/utils"
13+
"github.com/ethereum/go-ethereum/crypto"
14+
"github.com/pborman/uuid"
15+
"gopkg.in/urfave/cli.v1"
16+
)
17+
18+
type outputGenerate struct {
19+
Address string
20+
AddressEIP55 string
21+
}
22+
23+
var commandGenerate = cli.Command{
24+
Name: "generate",
25+
Usage: "generate new keyfile",
26+
ArgsUsage: "[ <keyfile> ]",
27+
Description: `
28+
Generate a new keyfile.
29+
If you want to use an existing private key to use in the keyfile, it can be
30+
specified by setting --privatekey with the location of the file containing the
31+
private key.`,
32+
Flags: []cli.Flag{
33+
passphraseFlag,
34+
jsonFlag,
35+
cli.StringFlag{
36+
Name: "privatekey",
37+
Usage: "the file from where to read the private key to " +
38+
"generate a keyfile for",
39+
},
40+
},
41+
Action: func(ctx *cli.Context) error {
42+
// Check if keyfile path given and make sure it doesn't already exist.
43+
keyfilepath := ctx.Args().First()
44+
if keyfilepath == "" {
45+
keyfilepath = defaultKeyfileName
46+
}
47+
if _, err := os.Stat(keyfilepath); err == nil {
48+
utils.Fatalf("Keyfile already exists at %s.", keyfilepath)
49+
} else if !os.IsNotExist(err) {
50+
utils.Fatalf("Error checking if keyfile exists: %v", err)
51+
}
52+
53+
var privateKey *ecdsa.PrivateKey
54+
55+
// First check if a private key file is provided.
56+
privateKeyFile := ctx.String("privatekey")
57+
if privateKeyFile != "" {
58+
privateKeyBytes, err := ioutil.ReadFile(privateKeyFile)
59+
if err != nil {
60+
utils.Fatalf("Failed to read the private key file '%s': %v",
61+
privateKeyFile, err)
62+
}
63+
64+
pk, err := crypto.HexToECDSA(string(privateKeyBytes))
65+
if err != nil {
66+
utils.Fatalf(
67+
"Could not construct ECDSA private key from file content: %v",
68+
err)
69+
}
70+
privateKey = pk
71+
}
72+
73+
// If not loaded, generate random.
74+
if privateKey == nil {
75+
pk, err := ecdsa.GenerateKey(crypto.S256(), rand.Reader)
76+
if err != nil {
77+
utils.Fatalf("Failed to generate random private key: %v", err)
78+
}
79+
privateKey = pk
80+
}
81+
82+
// Create the keyfile object with a random UUID.
83+
id := uuid.NewRandom()
84+
key := &keystore.Key{
85+
Id: id,
86+
Address: crypto.PubkeyToAddress(privateKey.PublicKey),
87+
PrivateKey: privateKey,
88+
}
89+
90+
// Encrypt key with passphrase.
91+
passphrase := getPassPhrase(ctx, true)
92+
keyjson, err := keystore.EncryptKey(key, passphrase,
93+
keystore.StandardScryptN, keystore.StandardScryptP)
94+
if err != nil {
95+
utils.Fatalf("Error encrypting key: %v", err)
96+
}
97+
98+
// Store the file to disk.
99+
if err := os.MkdirAll(filepath.Dir(keyfilepath), 0700); err != nil {
100+
utils.Fatalf("Could not create directory %s", filepath.Dir(keyfilepath))
101+
}
102+
if err := ioutil.WriteFile(keyfilepath, keyjson, 0600); err != nil {
103+
utils.Fatalf("Failed to write keyfile to %s: %v", keyfilepath, err)
104+
}
105+
106+
// Output some information.
107+
out := outputGenerate{
108+
Address: key.Address.Hex(),
109+
}
110+
if ctx.Bool(jsonFlag.Name) {
111+
mustPrintJSON(out)
112+
} else {
113+
fmt.Println("Address: ", out.Address)
114+
}
115+
return nil
116+
},
117+
}

‎cmd/ethkey/inspect.go‎

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
package main
2+
3+
import (
4+
"encoding/hex"
5+
"fmt"
6+
"io/ioutil"
7+
8+
"github.com/ethereum/go-ethereum/accounts/keystore"
9+
"github.com/ethereum/go-ethereum/cmd/utils"
10+
"github.com/ethereum/go-ethereum/crypto"
11+
"gopkg.in/urfave/cli.v1"
12+
)
13+
14+
type outputInspect struct {
15+
Address string
16+
PublicKey string
17+
PrivateKey string
18+
}
19+
20+
var commandInspect = cli.Command{
21+
Name: "inspect",
22+
Usage: "inspect a keyfile",
23+
ArgsUsage: "<keyfile>",
24+
Description: `
25+
Print various information about the keyfile.
26+
Private key information can be printed by using the --private flag;
27+
make sure to use this feature with great caution!`,
28+
Flags: []cli.Flag{
29+
passphraseFlag,
30+
jsonFlag,
31+
cli.BoolFlag{
32+
Name: "private",
33+
Usage: "include the private key in the output",
34+
},
35+
},
36+
Action: func(ctx *cli.Context) error {
37+
keyfilepath := ctx.Args().First()
38+
39+
// Read key from file.
40+
keyjson, err := ioutil.ReadFile(keyfilepath)
41+
if err != nil {
42+
utils.Fatalf("Failed to read the keyfile at '%s': %v", keyfilepath, err)
43+
}
44+
45+
// Decrypt key with passphrase.
46+
passphrase := getPassPhrase(ctx, false)
47+
key, err := keystore.DecryptKey(keyjson, passphrase)
48+
if err != nil {
49+
utils.Fatalf("Error decrypting key: %v", err)
50+
}
51+
52+
// Output all relevant information we can retrieve.
53+
showPrivate := ctx.Bool("private")
54+
out := outputInspect{
55+
Address: key.Address.Hex(),
56+
PublicKey: hex.EncodeToString(
57+
crypto.FromECDSAPub(&key.PrivateKey.PublicKey)),
58+
}
59+
if showPrivate {
60+
out.PrivateKey = hex.EncodeToString(crypto.FromECDSA(key.PrivateKey))
61+
}
62+
63+
if ctx.Bool(jsonFlag.Name) {
64+
mustPrintJSON(out)
65+
} else {
66+
fmt.Println("Address: ", out.Address)
67+
fmt.Println("Public key: ", out.PublicKey)
68+
if showPrivate {
69+
fmt.Println("Private key: ", out.PrivateKey)
70+
}
71+
}
72+
return nil
73+
},
74+
}

‎cmd/ethkey/main.go‎

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
// Copyright 2017 The go-ethereum Authors
2+
// This file is part of go-ethereum.
3+
//
4+
// go-ethereum is free software: you can redistribute it and/or modify
5+
// it under the terms of the GNU General Public License as published by
6+
// the Free Software Foundation, either version 3 of the License, or
7+
// (at your option) any later version.
8+
//
9+
// go-ethereum is distributed in the hope that it will be useful,
10+
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11+
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12+
// GNU General Public License for more details.
13+
//
14+
// You should have received a copy of the GNU General Public License
15+
// along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
16+
17+
package main
18+
19+
import (
20+
"fmt"
21+
"os"
22+
23+
"github.com/ethereum/go-ethereum/cmd/utils"
24+
"gopkg.in/urfave/cli.v1"
25+
)
26+
27+
const (
28+
defaultKeyfileName = "keyfile.json"
29+
)
30+
31+
var (
32+
gitCommit = "" // Git SHA1 commit hash of the release (set via linker flags)
33+
34+
app *cli.App // the main app instance
35+
)
36+
37+
var ( // Commonly used command line flags.
38+
passphraseFlag = cli.StringFlag{
39+
Name: "passwordfile",
40+
Usage: "the file that contains the passphrase for the keyfile",
41+
}
42+
43+
jsonFlag = cli.BoolFlag{
44+
Name: "json",
45+
Usage: "output JSON instead of human-readable format",
46+
}
47+
48+
messageFlag = cli.StringFlag{
49+
Name: "message",
50+
Usage: "the file that contains the message to sign/verify",
51+
}
52+
)
53+
54+
// Configure the app instance.
55+
func init() {
56+
app = utils.NewApp(gitCommit, "an Ethereum key manager")
57+
app.Commands = []cli.Command{
58+
commandGenerate,
59+
commandInspect,
60+
commandSignMessage,
61+
commandVerifyMessage,
62+
}
63+
}
64+
65+
func main() {
66+
if err := app.Run(os.Args); err != nil {
67+
fmt.Fprintln(os.Stderr, err)
68+
os.Exit(1)
69+
}
70+
}

0 commit comments

Comments
 (0)