github.com/luckypickle/go-ethereum-vet@v1.14.2/cmd/ethkey/changepassphrase.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"io/ioutil"
     6  	"strings"
     7  
     8  	"github.com/luckypickle/go-ethereum-vet/accounts/keystore"
     9  	"github.com/luckypickle/go-ethereum-vet/cmd/utils"
    10  	"gopkg.in/urfave/cli.v1"
    11  )
    12  
    13  var newPassphraseFlag = cli.StringFlag{
    14  	Name:  "newpasswordfile",
    15  	Usage: "the file that contains the new passphrase for the keyfile",
    16  }
    17  
    18  var commandChangePassphrase = cli.Command{
    19  	Name:      "changepassphrase",
    20  	Usage:     "change the passphrase on a keyfile",
    21  	ArgsUsage: "<keyfile>",
    22  	Description: `
    23  Change the passphrase of a keyfile.`,
    24  	Flags: []cli.Flag{
    25  		passphraseFlag,
    26  		newPassphraseFlag,
    27  	},
    28  	Action: func(ctx *cli.Context) error {
    29  		keyfilepath := ctx.Args().First()
    30  
    31  		// Read key from file.
    32  		keyjson, err := ioutil.ReadFile(keyfilepath)
    33  		if err != nil {
    34  			utils.Fatalf("Failed to read the keyfile at '%s': %v", keyfilepath, err)
    35  		}
    36  
    37  		// Decrypt key with passphrase.
    38  		passphrase := getPassphrase(ctx)
    39  		key, err := keystore.DecryptKey(keyjson, passphrase)
    40  		if err != nil {
    41  			utils.Fatalf("Error decrypting key: %v", err)
    42  		}
    43  
    44  		// Get a new passphrase.
    45  		fmt.Println("Please provide a new passphrase")
    46  		var newPhrase string
    47  		if passFile := ctx.String(newPassphraseFlag.Name); passFile != "" {
    48  			content, err := ioutil.ReadFile(passFile)
    49  			if err != nil {
    50  				utils.Fatalf("Failed to read new passphrase file '%s': %v", passFile, err)
    51  			}
    52  			newPhrase = strings.TrimRight(string(content), "\r\n")
    53  		} else {
    54  			newPhrase = promptPassphrase(true)
    55  		}
    56  
    57  		// Encrypt the key with the new passphrase.
    58  		newJson, err := keystore.EncryptKey(key, newPhrase, keystore.StandardScryptN, keystore.StandardScryptP)
    59  		if err != nil {
    60  			utils.Fatalf("Error encrypting with new passphrase: %v", err)
    61  		}
    62  
    63  		// Then write the new keyfile in place of the old one.
    64  		if err := ioutil.WriteFile(keyfilepath, newJson, 600); err != nil {
    65  			utils.Fatalf("Error writing new keyfile to disk: %v", err)
    66  		}
    67  
    68  		// Don't print anything.  Just return successfully,
    69  		// producing a positive exit code.
    70  		return nil
    71  	},
    72  }