
Educational Python simulation demonstrating ECDSA nonce reuse in IoT firmware signing, showing how an attacker can recover private keys from two signatures sharing the same k.
# ecdsa_nonce_reuse_sim.py - Signing firmware with repeated nonce (k)
import ecdsa, hashlib
sk = ecdsa.SigningKey.generate(curve=ecdsa.NIST256p)
vk = sk.get_verifying_key()
# Sign two different firmware images with same nonce due to bad RNG
# In reality, this can happen with deterministic k if seed is constant.
# We'll simulate by using the same k manually (not possible with ecdsa library, so fake it)
def sign_with_fixed_k(sk, msg_hash, k):
# Simplified: return signature (r,s) using fixed k (for educational purposes)
# Not actual ECDSA, but shows concept.
r = (k * ecdsa.NIST256p.generator).x()
k_inv = pow(k, -1, ecdsa.NIST256p.order)
s = k_inv * (int.from_bytes(msg_hash, 'big') + r * sk.privkey.secret_multiplier) % ecdsa.NIST256p.order
return ecdsa.ecdsa.Signature(r, s)
msg1 = b"Firmware v1.0"
msg2 = b"Firmware v2.0"
h1 = hashlib.sha256(msg1).digest()
h2 = hashlib.sha256(msg2).digest()
# Use same k
k = 123456789
sig1 = sign_with_fixed_k(sk, h1, k)
sig2 = sign_with_fixed_k(sk, h2, k)
print("Two signatures with same k. Attacker can recover private key from (r,s1) and (r,s2).")
某 IoT 设备使用 ECDSA 对固件更新进行签名,但由于随机数生成器薄弱,两个签名复用了同一个 nonce(k)。观察到这两个签名的攻击者可以计算出私钥,并签署恶意固件。
k 的签名,可以通过代数方法推导出私钥。运行模拟:
pip install ecdsa
python ecdsa_nonce_reuse_sim.py
该脚本演示了使用相同 k 创建两个签名的过程。真实的攻击者会利用公式 k = (h1 - h2) / (s1 - s2) 恢复密钥,然后通过 d = (s1*k - h1) / r 计算私钥。