我想知道是否有一种简单的方法(也许是一个库)来用 Python 编写常量时间程序。特别是,我希望能够指定 if-else 流必须始终持续同一时间,无论 if 条件是
True
还是 False
。
例如:
if condition:
foo1()
else:
foo2()
foo3()
以恒定时间运行此程序意味着命中
f3()
所需的时间应该相同,而与 condition
的评估结果无关。这将防止可能揭示 f1()
或 f2()
执行的侧通道(参见 定时攻击)。
由于您的问题是关于安全性的,我假设我们可以抛开性能并非常天真地介绍花在所有可能分支上的最短时间。实现此目的的一种方法是使用上下文管理器:
你的问题可以写成:
with ConstantTime(0.1):
if condition:
foo1()
else:
foor2()
foo3()
使用这样定义的上下文管理器:
import threading
import time
class ConstantTime():
def __init__(self, length):
self.length = length
def __enter__(self):
self.timer = threading.Thread(target=time.sleep, args=[self.length])
self.timer.start()
def __exit__(self, exc_type, exc_value, traceback):
self.timer.join()
当然,您必须根据自己在做什么,将实际时间调整为实际值。
一般来说,你不能确定你选择的分支不会超过你的最小时间,因为 Python 是一种非常高级的语言,你可能没有在实时操作系统中运行它,但是如果你设法涵盖平均运行时间,您应该显着减少从时序分析中收集的信息。