Solidity 中的哈希是什么?

加密哈希函数是一种算法,它以任意数量的数据作为输入并生成固定大小的加密文本。即使输入的微小变化也会产生完全不同的输出。

Solidity 提供以下加密功能:

功能

特性

keccak256(bytes memory) 返回 (bytes32) 计算输入的 Keccak-256 哈希
sha256(bytes memory) 返回 (bytes32) 计算输入的 SHA-256 哈希
ripemd160(bytes memory) 返回 (bytes20)  计算输入的 RIPEMD-160 哈希
sha256(bytes memory) 返回 (bytes32)  计算输入的 SHA-256 哈希
ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) 返回(地址)
从用于加密的椭圆曲线签名 中恢复与公钥关联的地址, 
如果发生错误则返回零。这些参数对应于 ECDSA 
签名值。

以太坊使用 Keccak 进行散列,这与 SHA_256 相似但不同。对于工作量证明,它使用了一种名为ethash的自定义方案,该方案旨在抗 ASIC。

示例:在下面的示例

// pragma version
pragma solidity ^0.6.6;

// Creating a contract
contract helloGeeks
{
	// We want hash to be of 8 digits
	// hence we store 10^8 which is
	// used to extract first 8 digits
	// later by Modulus
	uint hashDigits = 8;
	
	// Equivalent to 10^8 = 8
	uint hashModulus = 10 ** hashDigits;

	// Function to generate the hash value
	function _generateRandom(string memory _str)
		public view returns (uint)
	{
		// "packing" the string into bytes and
		// then applying the hash function.
		// This is then typecasted into uint.
		uint random =
			uint(keccak256(abi.encodePacked(_str)));
			
		// Returning the generated hash value
		return random % hashModulus;
	}

}

中,创建了一个智能合约以将字符串作为输入并给出 8 位哈希作为输出。

输入:

极客换极客

输出:

猜你喜欢

转载自blog.csdn.net/m0_73054711/article/details/126238511