github.com/ethxdao/go-ethereum@v0.0.0-20221218102228-5ae34a9cc189/cmd/ethkey/changepassword.go (about) 1 // Copyright 2018 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 "strings" 23 24 "github.com/ethxdao/go-ethereum/accounts/keystore" 25 "github.com/ethxdao/go-ethereum/cmd/utils" 26 ) 27 28 var newPassphraseFlag = &cli.StringFlag{ 29 Name: "newpasswordfile", 30 Usage: "the file that contains the new password for the keyfile", 31 } 32 33 var commandChangePassphrase = &cli.Command{ 34 Name: "changepassword", 35 Usage: "change the password on a keyfile", 36 ArgsUsage: "<keyfile>", 37 Description: ` 38 Change the password of a keyfile.`, 39 Flags: []cli.Flag{ 40 passphraseFlag, 41 newPassphraseFlag, 42 }, 43 Action: func(ctx *cli.Context) error { 44 keyfilepath := ctx.Args().First() 45 46 // Read key from file. 47 keyjson, err := os.ReadFile(keyfilepath) 48 if err != nil { 49 utils.Fatalf("Failed to read the keyfile at '%s': %v", keyfilepath, err) 50 } 51 52 // Decrypt key with passphrase. 53 passphrase := getPassphrase(ctx, false) 54 key, err := keystore.DecryptKey(keyjson, passphrase) 55 if err != nil { 56 utils.Fatalf("Error decrypting key: %v", err) 57 } 58 59 // Get a new passphrase. 60 fmt.Println("Please provide a new password") 61 var newPhrase string 62 if passFile := ctx.String(newPassphraseFlag.Name); passFile != "" { 63 content, err := os.ReadFile(passFile) 64 if err != nil { 65 utils.Fatalf("Failed to read new password file '%s': %v", passFile, err) 66 } 67 newPhrase = strings.TrimRight(string(content), "\r\n") 68 } else { 69 newPhrase = utils.GetPassPhrase("", true) 70 } 71 72 // Encrypt the key with the new passphrase. 73 newJson, err := keystore.EncryptKey(key, newPhrase, keystore.StandardScryptN, keystore.StandardScryptP) 74 if err != nil { 75 utils.Fatalf("Error encrypting with new password: %v", err) 76 } 77 78 // Then write the new keyfile in place of the old one. 79 if err := os.WriteFile(keyfilepath, newJson, 0600); err != nil { 80 utils.Fatalf("Error writing new keyfile to disk: %v", err) 81 } 82 83 // Don't print anything. Just return successfully, 84 // producing a positive exit code. 85 return nil 86 }, 87 }