LFSR and its reverse stepping
LFSR (Linear Feedback Shift Register) is a PRNG that is very cheap in hardware. The register is shifted by one position at each step, the outgoing bit is added to the keystream, and the XOR sum of the selected bits (feedback) is written to the vacated space.
The polynomial determines which bits are XORed. We used x^16 + x^14 + x^13 + x^11 + 1 — this is a classic polynomial with a maximum period (2^16 - 1 = 65535 steps).
Like LCG, LFSR also runs backwards. Because after the shift, the highest bit holds exactly the feedback bit: knowing it, shifting the register to the left, the lost lowest bit can be found from the XOR equation. Thus, it is possible to return from the final state to the initial state.
Encryption code:
def qadam(s): # s — 16 bitli registr
# x^16 + x^14 + x^13 + x^11 + 1 -> 0, 2, 3, 5 bitlari
bit = (s ^ (s >> 2) ^ (s >> 3) ^ (s >> 5)) & 1
chiqish = s & 1 # registrdan chiqib ketayotgan bit
s = (s >> 1) | (bit << 15) # oʻngga surish, chapga teskari aloqa
return s, chiqish
s = urug # 0 dan farqli 16 bitli boshlangʻich holat
kalit = []
for _ in range(39): # har bir bayt uchun 8 ta qadam
b = 0
for _ in range(8):
s, o = qadam(s)
b = (b << 1) | o # bitlar yuqoridan pastga yigʻiladi
kalit.append(b)
ct = bytes(x ^ k for x, k in zip(bayroq, kalit))
print('oxirgi holat:', hex(s))
The last state printed by the program:
oxirgi holat: 0xd732
Encrypted flag (hex):
dabf7a619f4968eae59d6b3c1efd0c30cf7a62fcc10d66063cc4f265706b06e8
100b99f056dba0
Derive the backward step yourself: oldin = (s << 1) & 0xFFFF, then the 0-th bit of oldin is found from the feedback equation.