Skip to content

Add native cryptographically secure random source - #837

Closed
victormeloasm wants to merge 1 commit into
bendlang:mainfrom
victormeloasm:native-csprng
Closed

victormeloasm wants to merge 1 commit into
bendlang:mainfrom
victormeloasm:native-csprng

Conversation

@victormeloasm

Copy link
Copy Markdown
Contributor

Adds a native cryptographically secure random source through IO.random_u32.

The existing deterministic RNG API remains unchanged for source and behavioral compatibility:

rnew
rnext
rrange

The original xorshift32 behavior is preserved exactly, including the existing rand.bend result of 4323489.

A separate cryptographically secure API is added:

rnew.secure
rnext.secure
rrange.secure
rclose.secure

The native entropy source uses:

Linux: getrandom()

macOS: arc4random_buf()

JavaScript: node:crypto.randomFillSync()

rrange.secure uses rejection sampling to avoid modulo bias and limits rejection attempts to 128 draws.

The implementation fails closed if the host cryptographic random source is unavailable and does not fall back to a deterministic PRNG.

The legacy API remains unchanged so existing consumers continue to compile and behave exactly as before.

@victormeloasm victormeloasm changed the title add native cryptographic secure random source Add native cryptographically secure random source Sep 18, 2026
VictorTaelin added a commit that referenced this pull request Sep 19, 2026
…ble seed had to carry its own effect; IO.random_u32 now answers one word from getrandom on Linux, arc4random_buf on macOS and crypto.getRandomValues on the JS lane (#837)

Co-authored-by: Victor Duarte Melo <[email protected]>
@VictorTaelin

Copy link
Copy Markdown
Contributor

Taken in part, in 2.0.13: IO.random_u32 is in Base with the two effs, rewritten to the style of the neighbouring effects (getrandom on Linux, arc4random_buf on macOS, crypto.getRandomValues on the JS lane), credited as co-author. The rewrite of tests/base/rand.bend was not taken: the secure API there was unused, and users can build a generator on top of IO.random_u32 in their own code.

Note: this reply was written by an AI after it reported the issue to me and I made the decision. If anything here is wrong, reply and I will review it myself.

Phylliida pushed a commit to Phylliida/bend that referenced this pull request Sep 27, 2026
…ble seed had to carry its own effect; IO.random_u32 now answers one word from getrandom on Linux, arc4random_buf on macOS and crypto.getRandomValues on the JS lane (bendlang#837)

Co-authored-by: Victor Duarte Melo <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants