Skip to content

Commit

Permalink
add encryptKey cli command (okx#221)
Browse files Browse the repository at this point in the history
  • Loading branch information
tclemos authored Jan 14, 2022
1 parent 33b9520 commit aae92c4
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
54 changes: 54 additions & 0 deletions cmd/encryptkey.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package main

import (
"log"
"strings"

"github.com/ethereum/go-ethereum/accounts/keystore"
"github.com/ethereum/go-ethereum/crypto"
"github.com/urfave/cli/v2"
)

const (
encryptKeyFlagPrivateKey = "privateKey"
encryptKeyFlagPassword = "password"
encryptKeyFlagOutput = "output"
)

var encryptKeyFlags = []cli.Flag{
&cli.StringFlag{
Name: encryptKeyFlagPrivateKey,
Aliases: []string{"pk"},
Usage: "Private key hash",
Required: true,
},
&cli.StringFlag{
Name: encryptKeyFlagPassword,
Aliases: []string{"pw"},
Usage: "Password to encrypt the private key",
Required: true,
},
&cli.StringFlag{
Name: encryptKeyFlagOutput,
Aliases: []string{"o"},
Usage: "Output directory to save the encrypted private key file",
Required: true,
},
}

func encryptKey(ctx *cli.Context) error {
privateKeyHash := ctx.String(encryptKeyFlagPrivateKey)
password := ctx.String(encryptKeyFlagPassword)
outputDir := ctx.String(encryptKeyFlagOutput)

privateKey, err := crypto.HexToECDSA(strings.TrimPrefix(privateKeyHash, "0x"))
if err != nil {
log.Fatal("Invalid private key: ", err)
}

ks := keystore.NewKeyStore(outputDir, keystore.StandardScryptN, keystore.StandardScryptP)
if _, err := ks.ImportECDSA(privateKey, password); err != nil {
log.Fatal("Failed to encrypt private key: ", err)
}
return nil
}
7 changes: 7 additions & 0 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,13 @@ func main() {
Action: registerSequencer,
Flags: flags,
},
{
Name: "encryptKey",
Aliases: []string{},
Usage: "Encrypts the privatekey with a password and create a keystore file",
Action: encryptKey,
Flags: encryptKeyFlags,
},
}

err := app.Run(os.Args)
Expand Down

0 comments on commit aae92c4

Please sign in to comment.