This mini-post breaks down how to solve for the constants of an Linear Congruential Generator (LCG) given:
- known power-of-two modulus (going to use 32-bit)
- three sequential outputs
Recall that LCGs (with implied mod) can be written as:
where
Let’s solve for
To isolate
We can now solve for
and while we’re at it for the seed
and “Bob’s your uncle”. Code given below. So the only tricky part in this simplified case is being aware of the mod inverse. This extends to other “bases” by updating the inverse function and performing the mod at each step. If the base is an unkown, then things get a bit more tricky (SEE: How to crack a Linear Congruential Generator)
uint32_t mod_inverse(uint32_t a)
{
uint32_t x;
x = 3*a ^ 2;
x *= 2-a*x;
x *= 2-a*x;
x *= 2-a*x;
return x;
}
typedef struct { uint32_t m; uint32_t c; uint32_t u0; } lcg_t;
void solve_lcg(lcg_t* data, uint32_t u1, uint32_t u2, uint32_t u3)
{
uint32_t m = (u2-u3)*mod_inverse(u1-u2);
uint32_t c = u2-m*u1;
data->m = m;
data->c = c;
data->u0 = mod_inverse(m)*(u1-c);
}