使用solidity智能合约实现sha256加密和验证

智能合约的sha256计算是基于bytes的而不是string的,如果想计算string的sha256加密值,要先编码字符串为byte类型才能计算。

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract HTLC {
    
    

    // 计算字符串的SHA-256哈希值
    function calculateSHA256(string memory input) public pure returns (bytes32) {
    
    
        return sha256(abi.encodePacked(input));
    }

    // 计算任意数据的SHA-256哈希值
    function calculateSHA256ForData(bytes memory input) public pure returns (bytes32) {
    
    
        return sha256(input);
    }

    function withdraw(bytes32 _secret, bytes32 _preimage) public pure returns (bool) {
    
    
        require(sha256(abi.encodePacked(_preimage)) == _secret, "Invalid preimage");
        // 执行提取操作,例如发送资金等
        return true;
    }

}

猜你喜欢

转载自blog.csdn.net/weixin_47485810/article/details/141284802