|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | + |
| 4 | +""" |
| 5 | +比特币密码学完整代码示例 |
| 6 | +包含本章节涉及的所有密码学操作实现 |
| 7 | +
|
| 8 | +依赖安装: |
| 9 | +pip install ecdsa mnemonic base58 cryptography |
| 10 | +
|
| 11 | +使用方法: |
| 12 | +python crypto_examples.py |
| 13 | +""" |
| 14 | + |
| 15 | +import hashlib |
| 16 | +import time |
| 17 | +import ecdsa |
| 18 | +from ecdsa import SigningKey, SECP256k1 |
| 19 | +import binascii |
| 20 | +import secrets |
| 21 | +import base58 |
| 22 | +import hmac |
| 23 | +import struct |
| 24 | +import os |
| 25 | +import base64 |
| 26 | +from mnemonic import Mnemonic |
| 27 | +from cryptography.fernet import Fernet |
| 28 | + |
| 29 | +class BitcoinCrypto: |
| 30 | + """比特币密码学工具包""" |
| 31 | + |
| 32 | + def __init__(self): |
| 33 | + self.curve_params = { |
| 34 | + 'p': 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F, |
| 35 | + 'n': 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141, |
| 36 | + 'Gx': 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798, |
| 37 | + 'Gy': 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8 |
| 38 | + } |
| 39 | + |
| 40 | + def sha256(self, data): |
| 41 | + """SHA-256哈希""" |
| 42 | + if isinstance(data, str): |
| 43 | + data = data.encode('utf-8') |
| 44 | + return hashlib.sha256(data).hexdigest() |
| 45 | + |
| 46 | + def double_sha256(self, data): |
| 47 | + """双重SHA-256(比特币标准)""" |
| 48 | + if isinstance(data, str): |
| 49 | + data = data.encode('utf-8') |
| 50 | + first = hashlib.sha256(data).digest() |
| 51 | + return hashlib.sha256(first).hexdigest() |
| 52 | + |
| 53 | + def demonstrate_avalanche_effect(self): |
| 54 | + """演示雪崩效应""" |
| 55 | + print("=== SHA-256雪崩效应演示 ===") |
| 56 | + original = "Hello Bitcoin" |
| 57 | + modified = "Hello bitcoin" |
| 58 | + |
| 59 | + print(f"原始: '{original}' -> {self.sha256(original)}") |
| 60 | + print(f"修改: '{modified}' -> {self.sha256(modified)}") |
| 61 | + print("结论: 微小改动导致完全不同的哈希值\n") |
| 62 | + |
| 63 | + def simple_proof_of_work(self, data, difficulty=4): |
| 64 | + """简化工作量证明演示""" |
| 65 | + print(f"=== 挖矿演示 (难度{difficulty}) ===") |
| 66 | + target = "0" * difficulty |
| 67 | + nonce = 0 |
| 68 | + start_time = time.time() |
| 69 | + |
| 70 | + while True: |
| 71 | + test_data = f"{data}{nonce}" |
| 72 | + hash_result = self.sha256(test_data) |
| 73 | + |
| 74 | + if hash_result.startswith(target): |
| 75 | + elapsed = time.time() - start_time |
| 76 | + print(f"挖矿成功! Nonce: {nonce}, 耗时: {elapsed:.2f}秒") |
| 77 | + print(f"哈希: {hash_result}\n") |
| 78 | + break |
| 79 | + nonce += 1 |
| 80 | + |
| 81 | + def generate_keypair(self): |
| 82 | + """生成比特币密钥对""" |
| 83 | + private_key = secrets.randbelow(self.curve_params['n']) |
| 84 | + signing_key = SigningKey.from_secret_exponent(private_key, curve=SECP256k1) |
| 85 | + |
| 86 | + return { |
| 87 | + 'private_key': hex(private_key), |
| 88 | + 'public_key_compressed': self.compress_public_key(signing_key.verifying_key), |
| 89 | + 'signing_key': signing_key |
| 90 | + } |
| 91 | + |
| 92 | + def compress_public_key(self, verifying_key): |
| 93 | + """压缩公钥格式""" |
| 94 | + point = verifying_key.pubkey.point |
| 95 | + x, y = point.x(), point.y() |
| 96 | + prefix = '03' if y % 2 == 1 else '02' |
| 97 | + return prefix + f'{x:064x}' |
| 98 | + |
| 99 | + def sign_and_verify(self, message, keypair): |
| 100 | + """数字签名演示""" |
| 101 | + print("=== 数字签名演示 ===") |
| 102 | + print(f"消息: {message}") |
| 103 | + |
| 104 | + # 签名 |
| 105 | + message_hash = hashlib.sha256(message.encode()).digest() |
| 106 | + signature = keypair['signing_key'].sign(message_hash) |
| 107 | + sig_hex = binascii.hexlify(signature).decode() |
| 108 | + |
| 109 | + print(f"签名: {sig_hex[:32]}...") |
| 110 | + |
| 111 | + # 验证 |
| 112 | + try: |
| 113 | + keypair['signing_key'].verifying_key.verify(signature, message_hash) |
| 114 | + print("✅ 签名验证成功") |
| 115 | + except: |
| 116 | + print("❌ 签名验证失败") |
| 117 | + |
| 118 | + # 篡改测试 |
| 119 | + tampered = message + "x" |
| 120 | + tampered_hash = hashlib.sha256(tampered.encode()).digest() |
| 121 | + try: |
| 122 | + keypair['signing_key'].verifying_key.verify(signature, tampered_hash) |
| 123 | + print("❌ 篡改消息验证成功(不应该发生)") |
| 124 | + except: |
| 125 | + print("✅ 篡改消息验证失败(正确行为)\n") |
| 126 | + |
| 127 | + def private_key_to_address(self, private_key_hex): |
| 128 | + """从私钥生成比特币地址""" |
| 129 | + print("=== 地址生成过程 ===") |
| 130 | + |
| 131 | + # 1. 生成公钥 |
| 132 | + private_key_int = int(private_key_hex, 16) |
| 133 | + signing_key = SigningKey.from_secret_exponent(private_key_int, curve=SECP256k1) |
| 134 | + compressed_pubkey = self.compress_public_key(signing_key.verifying_key) |
| 135 | + print(f"1. 压缩公钥: {compressed_pubkey}") |
| 136 | + |
| 137 | + # 2. SHA-256 |
| 138 | + pubkey_bytes = bytes.fromhex(compressed_pubkey) |
| 139 | + sha256_hash = hashlib.sha256(pubkey_bytes).digest() |
| 140 | + |
| 141 | + # 3. RIPEMD-160 |
| 142 | + ripemd160_hash = hashlib.new('ripemd160', sha256_hash).digest() |
| 143 | + print(f"2. 公钥哈希: {ripemd160_hash.hex()}") |
| 144 | + |
| 145 | + # 4. 添加版本和校验和 |
| 146 | + versioned = b'\x00' + ripemd160_hash |
| 147 | + checksum = hashlib.sha256(hashlib.sha256(versioned).digest()).digest()[:4] |
| 148 | + |
| 149 | + # 5. Base58编码 |
| 150 | + address = base58.b58encode(versioned + checksum).decode() |
| 151 | + print(f"3. 比特币地址: {address}\n") |
| 152 | + |
| 153 | + return address |
| 154 | + |
| 155 | +class HDWallet: |
| 156 | + """简化的HD钱包实现""" |
| 157 | + |
| 158 | + def __init__(self, mnemonic_phrase=None): |
| 159 | + self.mnemo = Mnemonic('english') |
| 160 | + |
| 161 | + if mnemonic_phrase is None: |
| 162 | + self.mnemonic = self.mnemo.generate(strength=128) # 12个词 |
| 163 | + else: |
| 164 | + if not self.mnemo.check(mnemonic_phrase): |
| 165 | + raise ValueError("无效的助记词") |
| 166 | + self.mnemonic = mnemonic_phrase |
| 167 | + |
| 168 | + # 生成种子 |
| 169 | + self.seed = self.mnemo.to_seed(self.mnemonic) |
| 170 | + |
| 171 | + # 生成主私钥 |
| 172 | + master_key = hmac.new(b"Bitcoin seed", self.seed, hashlib.sha512).digest() |
| 173 | + self.master_private_key = master_key[:32] |
| 174 | + self.master_chain_code = master_key[32:] |
| 175 | + |
| 176 | + def derive_child(self, parent_key, parent_chain, index): |
| 177 | + """派生子密钥""" |
| 178 | + if index >= 0x80000000: # 硬化派生 |
| 179 | + data = b'\x00' + parent_key + struct.pack('>I', index) |
| 180 | + else: # 正常派生(简化实现) |
| 181 | + data = parent_key + struct.pack('>I', index) |
| 182 | + |
| 183 | + child_key = hmac.new(parent_chain, data, hashlib.sha512).digest() |
| 184 | + return child_key[:32], child_key[32:] |
| 185 | + |
| 186 | + def get_address(self, account=0, change=0, index=0): |
| 187 | + """获取指定路径的地址""" |
| 188 | + # 简化的BIP44路径派生 m/44'/0'/account'/change/index |
| 189 | + current_key = self.master_private_key |
| 190 | + current_chain = self.master_chain_code |
| 191 | + |
| 192 | + # 派生路径 |
| 193 | + for i in [44 + 0x80000000, 0x80000000, account + 0x80000000, change, index]: |
| 194 | + current_key, current_chain = self.derive_child(current_key, current_chain, i) |
| 195 | + |
| 196 | + # 生成地址 |
| 197 | + crypto = BitcoinCrypto() |
| 198 | + return crypto.private_key_to_address(current_key.hex()) |
| 199 | + |
| 200 | +class SecurityDemo: |
| 201 | + """安全最佳实践演示""" |
| 202 | + |
| 203 | + def secure_random_demo(self): |
| 204 | + """安全随机数生成演示""" |
| 205 | + print("=== 安全随机数生成 ===") |
| 206 | + |
| 207 | + # 不安全的方式 |
| 208 | + import random |
| 209 | + unsafe = random.randint(1, 2**256) |
| 210 | + print(f"❌ random模块: {hex(unsafe)[:20]}...") |
| 211 | + |
| 212 | + # 安全的方式 |
| 213 | + safe1 = secrets.randbelow(2**256) |
| 214 | + safe2 = int.from_bytes(os.urandom(32), 'big') |
| 215 | + |
| 216 | + print(f"✅ secrets模块: {hex(safe1)[:20]}...") |
| 217 | + print(f"✅ os.urandom: {hex(safe2)[:20]}...\n") |
| 218 | + |
| 219 | + def encrypt_private_key(self, private_key, password): |
| 220 | + """私钥加密示例""" |
| 221 | + print("=== 私钥加密演示 ===") |
| 222 | + |
| 223 | + # 使用PBKDF2派生密钥 |
| 224 | + salt = os.urandom(16) |
| 225 | + key = hashlib.pbkdf2_hmac('sha256', password.encode(), salt, 100000) |
| 226 | + key_base64 = base64.urlsafe_b64encode(key) |
| 227 | + |
| 228 | + # 加密私钥 |
| 229 | + f = Fernet(key_base64) |
| 230 | + encrypted = f.encrypt(private_key.encode()) |
| 231 | + |
| 232 | + print(f"原始私钥: {private_key}") |
| 233 | + print(f"盐值: {salt.hex()}") |
| 234 | + print(f"加密私钥: {encrypted.hex()[:32]}...") |
| 235 | + |
| 236 | + # 解密验证 |
| 237 | + decrypted = f.decrypt(encrypted).decode() |
| 238 | + print(f"解密成功: {'✅' if decrypted == private_key else '❌'}\n") |
| 239 | + |
| 240 | +def main(): |
| 241 | + """主演示程序""" |
| 242 | + print("🔐 比特币密码学完整演示\n") |
| 243 | + |
| 244 | + # 初始化工具 |
| 245 | + crypto = BitcoinCrypto() |
| 246 | + |
| 247 | + # 1. 哈希函数演示 |
| 248 | + crypto.demonstrate_avalanche_effect() |
| 249 | + crypto.simple_proof_of_work("比特币区块", difficulty=3) |
| 250 | + |
| 251 | + # 2. 数字签名演示 |
| 252 | + keypair = crypto.generate_keypair() |
| 253 | + crypto.sign_and_verify("从Alice转账1BTC给Bob", keypair) |
| 254 | + |
| 255 | + # 3. 地址生成演示 |
| 256 | + test_private_key = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" |
| 257 | + crypto.private_key_to_address(test_private_key) |
| 258 | + |
| 259 | + # 4. HD钱包演示 |
| 260 | + print("=== HD钱包演示 ===") |
| 261 | + hd_wallet = HDWallet() |
| 262 | + print(f"助记词: {hd_wallet.mnemonic}") |
| 263 | + |
| 264 | + # 生成几个地址 |
| 265 | + for i in range(3): |
| 266 | + addr = hd_wallet.get_address(account=0, change=0, index=i) |
| 267 | + print(f"地址{i}: {addr}") |
| 268 | + print() |
| 269 | + |
| 270 | + # 5. 安全演示 |
| 271 | + security = SecurityDemo() |
| 272 | + security.secure_random_demo() |
| 273 | + security.encrypt_private_key(test_private_key, "SecurePassword123!") |
| 274 | + |
| 275 | + print("🎉 演示完成!") |
| 276 | + |
| 277 | +if __name__ == "__main__": |
| 278 | + main() |
0 commit comments