DEV Community

abhinav the builder
abhinav the builder

Posted on


Passwords in Solidity

Why is it needed?

Suppose you have locked liquidity on-contract which can be liquidated via withdraw() that depends on a require function and access control. If someone has access to the responsible EOA, they can withdraw funds when needed. A better way to go about this is to also have a password, so that incase of a private key leak, the hacker still has to enter a password.

How is it implemented?

  1. User enters password, gets hashed via Keccak256 and appended with "0x" before the hash string.
  2. User sets password via constructor when deploying (_setNewPassword())
  3. User then can decide to check password (_testPassword()) and enter expected password and new password (since current password will be declared by on-chain data).

Solidity Code

contract onChainPassword
    bytes32 private globalPassword;

    constructor(bytes32 _hashedPassword) 
        globalPassword = _hashedPassword;

    function _checkPassword(string memory _password, bytes32 _newPassword)
        public returns (bool)
        bool decision = keccak256(abi.encodePacked(_password))==globalPassword;
        return decision;

    function _setNewPassword(bytes32 _newPassword) internal
        globalPassword = _newPassword;
Enter fullscreen mode Exit fullscreen mode


Never put Friday projects on main-net without testing extensively, I'm a scatterbrain.

Top comments (0)

Here is a post you might want to check out:

Regex for lazy developers

regex for lazy devs

Sorry for the callout 😆