Trong mật mã học hiện đại , PRNGS - bộ sinh số giả ngẫu nhiên đóng vai trò quan trọng trong việc tạo ra những dữ liệu trông có vẻ “ngẫu nhiên” như nonce hoặc key. Đối với PRNGS ta có ba khái niệm chung như sau:
Trên thực tế, không phải tất cả các PRNG đều được thiết kế an toàn và với một lượng thông tin nhất định ta có thể crack được bộ sinh và khôi phục lại seed cũng như dự đoán được giá trị tiếp theo của nó.
Link github: https://github.com/ken3k06/crack-random
Source của hàm: https://github.com/python/cpython/blob/23362f8c301f72bbf261b56e1af93e8c52f5b6cf/Modules/_randommodule.c
Thuật toán cho hàm random của Python được mặc định là Mersenne Twister MT19937
/* Period parameters -- These are all magic. Don't change. */
#define N 624
#define M 397
#define MATRIX_A 0x9908b0dfU /* constant vector a */
#define UPPER_MASK 0x80000000U /* most significant w-r bits */
#define LOWER_MASK 0x7fffffffU /* least significant r bits */
typedef struct {
PyObject *Random_Type;
PyObject *Long___abs__;
} _randomstate;
static inline _randomstate*
get_random_state(PyObject *module)
{
void *state = _PyModule_GetState(module);
assert(state != NULL);
return (_randomstate *)state;
}
static struct PyModuleDef _randommodule;
#define _randomstate_type(type) \\
(get_random_state(_PyType_GetModuleByDef(type, &_randommodule)))
typedef struct {
PyObject_HEAD
int index;
uint32_t state[N];
} RandomObject;
#include "clinic/_randommodule.c.h"
/*[clinic input]
module _random
class _random.Random "RandomObject *" "_randomstate_type(type)->Random_Type"
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=70a2c99619474983]*/
/* Random methods */
/* generates a random number on [0,0xffffffff]-interval */
static uint32_t
genrand_uint32(RandomObject *self)
{
uint32_t y;
static const uint32_t mag01[2] = {0x0U, MATRIX_A};
/* mag01[x] = x * MATRIX_A for x=0,1 */
uint32_t *mt;
mt = self->state;
if (self->index >= N) { /* generate N words at one time */
int kk;
for (kk=0;kk<N-M;kk++) {
y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1U];
}
for (;kk<N-1;kk++) {
y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1U];
}
y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK);
mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1U];
self->index = 0;
}
y = mt[self->index++];
y ^= (y >> 11);
y ^= (y << 7) & 0x9d2c5680U;
y ^= (y << 15) & 0xefc60000U;
y ^= (y >> 18);
return y;
}
Một cách tổng quát, thuật toán Mersenne Twister được triển khai bằng đệ quy, bởi biểu thức được gọi là Twist như sau
$$ \bold{{x}{k+n}} := \bold{x{k+m}} \oplus ((\bold{x_{k}^{w-r}} | \bold{x_{k+1}^{r}})\bold{A}) $$
Trong đó