My Image
CoursesQuizzesProblemsContestsSmartBooks
Contest!

No results found

LOGINREGISTER
My ProgressCoursesQuizzesProblemsContestsSmartbooks
Published on 6 Jul 2021
Create function to generate hash of username using sha256 function
Cryptographic Functions in Solidity
img
Rajendra Bisoi
0
Like
216

Function

Properties

keccak256(bytes memory) returns (bytes32)Computes the Keccak-256 hash of the input
sha256(bytes memory) returns (bytes32)Computes the SHA-256 hash of the input
ripemd160(bytes memory) returns (bytes20) Compute RIPEMD-160 hash of the input
ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) returns (address)

Recover the address associated with the public key from 
Elliptic curve signature used for cryptography or return 
Zero if an error occurs. The parameters correspond to ECDSA 
Signature values.

Here we want to take input arguments as string memory inside the function to get hash of the same; 


 function getRandomUserId(string memory _username) public view returns(bytes32){
        return sha256(abi.encodePacked(_username));  //returns a result of 32 bytes 
   }

 Suppose you are a curious and experimental nerd. You would like to return id of length as per user choice.Let's say you want to return the length of id generated to be 6. Then proceed like this.

  //Here in the input section you can take input of _length as 6 to satisfy your hunger
 function getRandomUserId(string memory _username, uint _length) public view returns (uint) 
    {
       uint hashModulus =  10 ** _length;      

        uint random = uint(sha256(abi.encodePacked(_username)));
    
        return random % hashModulus;
    }

 

Caution: 

Incase of ripemd160( ) it might not be feasible since it returns bytes20 & bytes20 can't be converted to uint256 explicitly

For many more exciting tutorials keep following my username @BlockTalks_Raj

!!!!!HAPPY LEARNING!!!!!

 
Enjoyed the SmartBook?
Like
logo
contact@dapp-world.com
Katraj, Pune, Maharashtra, India - 411048

Follow Us

linkedintwitteryoutubediscordinstagram

Products

  • SmartBooks
  • Courses
  • Quizzes
  • Assessments

Support

  • Contact Us
  • FAQ
  • Privacy Policy
  • T&C

Backed By

ah! ventures

Copyright 2023 - All Rights Reserved.

Recommended from DAppWorld
img
1 May 2021
How to connect Ganache with Metamask and deploy Smart contracts on remix without
Set up your development environment with (Metamask + Ganache + Remix) and skip truffle :)
3 min read
11508
5
img
8 Jul 2021
How to interact with smart contarct from backend node js
call and send functions from backend server side using nodejs
3 min read
8103
2
img
18 Aug 2021
Send transaction with web3 using python
Introduction to web3.py and sending transaction on testnet
3 min read
6229
5
img
5 Aug 2021
Deploy Smart Contract on Polygon POS using Hardhat
how to deploy smart contracts on polygon pos chain using hardhat both mainnet and testnet ?
3 min read
5540
3