You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
FileSecureTransfer/tool/hash/Segwit.py

73 lines
1.7 KiB

import hashlib
import bech32
# https://liaoxuefeng.com/books/blockchain/bitcoin/segwit/index.html
def hash160(data):
"""
计算输入数据的SHA-160哈希值
参数:
data (bytes): 输入数据
返回:
bytes: SHA-160哈希值
"""
return hashlib.new('ripemd160', hashlib.sha256(data).digest()).digest()
def encodeSegwit(data_bytes, hrp="fst"):
"""
将字节数据编码为Bech32格式
参数:
hrp (str): 人类可读部分 (Human-readable part)
data_bytes (bytes): 要编码的数据
返回:
str: Bech32编码后的字符串
"""
# 将字节转换为5位整数列表
data_ints = bech32.convertbits(hash160(data_bytes), 8, 5)
if not data_ints:
raise ValueError("Failed to convert bytes to 5-bit integers")
return bech32.bech32_encode(hrp, data_ints)
def verifySegwit(bech32_str):
"""
验证Bech32编码的字符串是否有效
参数:
bech32_str (str): Bech32编码的字符串
返回:
bool: 如果字符串有效则返回True否则返回False
"""
try:
hrp, data_ints = bech32.bech32_decode(bech32_str)
if not hrp or not data_ints:
return False
# 将5位整数列表转换回字节
data_bytes = bech32.convertbits(data_ints, 5, 8, False)
if not data_bytes:
return False
return True
except Exception as e:
print(f"Verification failed: {e}")
return False
# 示例用法
if __name__ == "__main__":
message = b"Hello, Bech32!"
encoded = encodeSegwit(message)
print(f"Encoded: {encoded}")
is_valid = verifySegwit(encoded)
print(f"Is valid: {is_valid}")