Loading...
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. |
In solidity we can generate random id of user name in two types
1st by calling simple "keccak256(stringInput)"
2nd by calling "keccak256(abi.encodePacked(stringInput))"
calling and generating random id for user name in 1st method
pragma solidity ^0.8.3;
contract task1 {
function getRandomUserId() public view returns(bytes32){
return keccak256("BlockTalks"); //returns a result of 32 bytes
}
}
But if we want to take input arguments as string memory inside the function; then the use 2nd method because the 1st method only takes bytes1 argument as input in keccak256 function or other cryptographic functions
function getRandomUserId(string memory _username) public view returns(bytes32){
return keccak256(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(keccak256(abi.encodePacked(_username)));
return random % hashModulus;
}
Caution:
And now onwards you can experiment on sha256( ) but 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!!!!!