X-Git-Url: https://git.lizzy.rs/?a=blobdiff_plain;f=sys%2Fsrc%2F9%2Fport%2Frandom.c;h=b27e5720dbd9c427f17ec62075c9ad8e7e9f4416;hb=4f85115526a87063489dc7cf347343bd520159b1;hp=d401e7e0181eccbe1f7a58b099cdbb64402f2c7c;hpb=7713145638f45c07c47b9ef8c859d518d88f6127;p=plan9front.git diff --git a/sys/src/9/port/random.c b/sys/src/9/port/random.c index d401e7e01..b27e5720d 100644 --- a/sys/src/9/port/random.c +++ b/sys/src/9/port/random.c @@ -89,7 +89,6 @@ ulong randomread(void *p, ulong n) { Chachastate c; - ulong b; if(n == 0) return 0; @@ -97,12 +96,13 @@ randomread(void *p, ulong n) if(hwrandbuf != nil) (*hwrandbuf)(p, n); - /* copy chacha state and advance block counter */ + /* copy chacha state, rekey and increment iv */ qlock(rs); c = *rs; - b = rs->input[12]; - rs->input[12] += (n + ChachaBsize-1)/ChachaBsize; - if(rs->input[12] < b) rs->input[13]++; + chacha_encrypt((uchar*)&rs->input[4], 32, &c); + if(++rs->input[13] == 0) + if(++rs->input[14] == 0) + ++rs->input[15]; qunlock(rs); /* encrypt the buffer, can fault */ @@ -120,3 +120,28 @@ genrandom(uchar *p, int n) { randomread(p, n); } + +/* used by rand(),nrand() */ +long +lrand(void) +{ + /* xoroshiro128+ algorithm */ + static int seeded = 0; + static uvlong s[2]; + static Lock lk; + ulong r; + + if(seeded == 0){ + randomread(s, sizeof(s)); + seeded = (s[0] | s[1]) != 0; + } + + lock(&lk); + r = (s[0] + s[1]) >> 33; + s[1] ^= s[0]; + s[0] = (s[0] << 55 | s[0] >> 9) ^ s[1] ^ (s[1] << 14); + s[1] = (s[1] << 36 | s[1] >> 28); + unlock(&lk); + + return r; +}