DEV Community

abhinav the builder
abhinav the builder

Posted on

4 3

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;
        _setNewPassword(_newPassword);
        return decision;
    }

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

Disclaimer

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

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay