Path: blob/master/attacks/mersenne_twister/state_recovery.py
2589 views
import os1import sys23path = os.path.dirname(os.path.dirname(os.path.realpath(os.path.abspath(__file__))))4if sys.path[1] != path:5sys.path.insert(1, path)67from attacks import mersenne_twister8910def _reverse_left(y, shift, mask, w):11y_ = 012for i in range(shift, w, shift):13m = 2 ** i - 114y_ = (y ^ ((y_ << shift) & mask)) & m15y_ = (y ^ ((y_ << shift) & mask)) & (2 ** w - 1)16return y_171819def _reverse_right(y, shift, mask, w):20y_ = 021for i in range(shift, w, shift):22m = (2 ** i - 1) << (w - i)23y_ = (y ^ ((y_ >> shift) & mask)) & m24y_ = (y ^ ((y_ >> shift) & mask)) & (2 ** w - 1)25return y_262728def _attack_mt(y, mt):29assert len(y) == mt.n30mt.index = 031while mt.index < mt.n:32yi = y[mt.index]33yi = _reverse_right(yi, mt.l, 2 ** mt.w - 1, mt.w)34yi = _reverse_left(yi, mt.t, mt.c, mt.w)35yi = _reverse_left(yi, mt.s, mt.b, mt.w)36yi = _reverse_right(yi, mt.u, mt.d, mt.w)37mt.mt[mt.index] = yi38mt.index += 139return mt404142def attack(y, w, n, m, r, a, b, c, s, t, u, d, l):43"""44Recovers the state from a Mersenne Twister instance using n outputs.45No twist should have been performed during the outputs.46:param y: the outputs (must be of length n)47:param w: the parameter w48:param n: the parameter n49:param m: the parameter m50:param r: the parameter r51:param a: the parameter a52:param b: the parameter b53:param c: the parameter c54:param s: the parameter s55:param t: the parameter t56:param u: the parameter u57:param d: the parameter d58:param l: the parameter l59:return: a cloned Mersenne Twister instance60"""61return _attack_mt(y, mersenne_twister.MersenneTwister(w, n, m, r, a, b, c, s, t, u, d, l))626364def attack_mt19937(y):65"""66Recovers the state from an MT19937 instance using 624 outputs.67No twist should have been performed during the outputs.68:param y: the outputs69:return: a cloned MT19937 instance70"""71return _attack_mt(y, mersenne_twister.mt19937())727374def attack_mt19937_64(y):75"""76Recovers the state from an MT19937-64 instance using 312 outputs.77No twist should have been performed during the outputs.78:param y: the outputs79:return: a cloned MT19937-64 instance80"""81return _attack_mt(y, mersenne_twister.mt19937_64())828384