solitidy官方文档
keccak256()SHA3
采用Keccak
算法,在不少场合下Keccak
和SHA3
是同义词,但在2015年8月SHA3最终完成标准化时,NIST调整了填充算法,标准的SHA3和原先的Keccak算法就有所区别了。在早期的Ethereum相关代码中,广泛使用SHA3代指Keccak256
,为了不和NIST标准的SHA3混淆,如今的代码直接使用Keccak256
做为函数名。html
keccak256(...) returns (bytes32)
// 紧密打包:参数不会补位,就直接链接在一块儿的。下面来看一个例子效果同样: keccak256("ab", "c") keccak256("abc") keccak256(0x616263) keccak256(6382179) keccak256(97, 98, 99)
椭圆曲线加密web
引用
pragma solidity ^0.4.4; contract Decode{ //公匙:0x60320b8a71bc314404ef7d194ad8cac0bee1e331 //sha3(msg): 0x4e03657aea45a94fc7d47ba826c8d667c0d1e6e33a64a036ec44f58fa12d6c45 (web3.sha3("abc");) //签名后的数据:0xf4128988cbe7df8315440adde412a8955f7f5ff9a5468a791433727f82717a6753bd71882079522207060b681fbd3f5623ee7ed66e33fc8e581f442acbcf6ab800 //验签数据入口函数 function decode() returns (address){ bytes memory signedString =hex"f4128988cbe7df8315440adde412a8955f7f5ff9a5468a791433727f82717a6753bd71882079522207060b681fbd3f5623ee7ed66e33fc8e581f442acbcf6ab800"; bytes32 r = bytesToBytes32(slice(signedString, 0, 32)); bytes32 s = bytesToBytes32(slice(signedString, 32, 32)); byte v = slice(signedString, 64, 1)[0]; return ecrecoverDecode(r, s, v); } //将原始数据按段切割出来指定长度 function slice(bytes memory data, uint start, uint len) returns (bytes){ bytes memory b = new bytes(len); for(uint i = 0; i < len; i++){ b[i] = data[i + start]; } return b; } //使用ecrecover恢复公匙 function ecrecoverDecode(bytes32 r, bytes32 s, byte v1) returns (address addr){ uint8 v = uint8(v1) + 27; addr = ecrecover(hex"4e03657aea45a94fc7d47ba826c8d667c0d1e6e33a64a036ec44f58fa12d6c45", v, r, s); } //bytes转换为bytes32 function bytesToBytes32(bytes memory source) returns (bytes32 result) { assembly { result := mload(add(source, 32)) } } }
上述代码使用临时写的slice()函数把数据签名中的r,s,v切割出来;因为返回的还是一个bytes类型,因此咱们使用bytesToBytes32()进行一下类型转换8;另外须要注意的是ecrecoverDecode()根据前面的说明,咱们须要对v值,加上27后再进行调用。最后调用decode()函数,咱们将会获得公匙0x60320b8a71bc314404ef7d194ad8cac0bee1e331。算法
bancor.network里面的验证算法 function verifyTrustedSender(IERC20Token[] _path, uint256 _amount, uint256 _block, address _addr, uint8 _v, bytes32 _r, bytes32 _s) private returns(bool) { bytes32 hash = keccak256(_block, tx.gasprice, _addr, msg.sender, _amount, _path); // checking that it is the first conversion with the given signature // and that the current block number doesn't exceeded the maximum block // number that's allowed with the current signature require(!conversionHashes[hash] && block.number <= _block); // recovering the signing address and comparing it to the trusted signer // address that was set in the contract bytes32 prefixedHash = keccak256("\x19Ethereum Signed Message:\n32", hash); bool verified = ecrecover(prefixedHash, _v, _r, _s) == signerAddress; // if the signer is the trusted signer - mark the hash so that it can't // be used multiple times if (verified) conversionHashes[hash] = true; return verified; }