安装cryptography后运行脚本报错:找不到mnemonic模块
问题与解决:cryptography模块找不到错误
问题详情
- 当前依赖版本:
- cffi==1.15.1
- cryptography==38.0.4
- pycparser==2.21
- 运行脚本时触发错误:
ModuleNotFoundError: No module named 'cryptography.hazmat.primitives.mnemonic' - 涉及脚本:
from cryptography.hazmat.primitives.mnemonic import Mnemonic from cryptography.hazmat.primitives.keys import HDPrivateKey # Ask the user for the mnemonic mnemonic = input("Please enter your mnemonic: ") # Create a Mnemonic object m = Mnemonic(language="english") # Convert the mnemonic to a seed seed = m.to_seed(mnemonic) # Derive the private key using the HDPrivateKey class and the desired derivation path priv_key = HDPrivateKey.from_seed(seed, "44/314159/0") # Output the private and public keys print("Private key:", priv_key.private_key.hex()) print("Public key:", priv_key.public_key.public_bytes(encoding=serialization.Encoding.HEX).decode())
原因分析
你的怀疑完全正确。cryptography.hazmat.primitives.mnemonic和HDPrivateKey这类模块在cryptography 3.4版本后被官方移除,它们原本属于hazmat(危险材料)层,官方出于安全维护考量,不再提供这类功能的支持,当前38.0.4版本自然没有这些模块。
解决方法
方法1:降级cryptography到旧版本
如果必须沿用原有脚本逻辑,可以降级到包含这些模块的最后一个稳定版本:
pip install cryptography==3.3.2
注意:旧版本存在已知安全漏洞,生产环境不建议使用。
方法2:替换为第三方专业库(推荐)
官方推荐使用专注于BIP-39/BIP-44标准的第三方库,比如mnemonic(处理助记词)和bip_utils(处理HD密钥推导),这类库维护更活跃、功能更专业。
步骤1:安装依赖
pip install mnemonic bip_utils
步骤2:修改后的可用脚本
from mnemonic import Mnemonic from bip_utils import Bip39SeedGenerator, Bip44, Bip44Coins # 获取用户输入的助记词 mnemonic = input("请输入你的助记词: ") # 验证助记词有效性并生成种子 m = Mnemonic("english") if not m.check(mnemonic): print("无效的助记词") exit() seed = Bip39SeedGenerator(mnemonic).Generate() # 按照指定路径推导HD私钥 bip44_ctx = Bip44.FromSeed(seed, Bip44Coins.BITCOIN).DerivePath("m/44'/314159'/0'/0/0") # 输出密钥 print("私钥:", bip44_ctx.PrivateKey().Raw().ToHex()) print("公钥:", bip44_ctx.PublicKey().RawCompressed().ToHex())
说明:
- 新增了助记词有效性校验逻辑
- 严格遵循BIP-44标准的路径推导规则(路径中的
'表示强化推导) - 修复了原脚本未导入
serialization模块的隐性问题
内容的提问来源于stack exchange,提问作者jdoe
相关产品推荐
相关产品推荐

