Search code examples
ethereumweb3js

Is there a way to change the private key associated to a web3 account?


I have a web3 account and private key with me. Lets say I have the 12 word mnuemoic too. Is there a way I can change my private key or rotate it when I want ?

If not, what should I do if my private key gets compromised. If yes, can you point me to the code or API in web3 which would help me do that ?


Solution

  • An address is generated from its private key. So when you change a private key, it always results in a different address.

    Note: It's statistically possible that there are multiple private keys to the same address. There are several researches but none have found a collision (a second private key generating the same address), as the probability is extremely low - practically impossible with our current technology.


    If the change of address is all right for you use case, you can add a new account to the web3 instance using the wallet.add() function (docs), or remove an account using the wallet.remove() function (docs).

    Unfortunately web3 only works with private keys - not with mnemonic phrases. So you'll need to generate the according private key from the mnemonic using a different package. For example the hdwallet-provider.