Skip to content

SecureRandom performance could be better #1405

@headius

Description

@headius

Our SecureRandom in 1.7.10 (from securerandom.rb) was implemented using Java integration calling out to java.security.SecureRandom. It constructed a new instance each time.

In 09b169a, I moved the meat of the logic (#random_bytes) into Java code, which roughly doubled performance on my machine, bringing it close to MRI.

@bbrowning and @nirvdrum discovered a JVM property that, when passed, sets SecureRandom to use /dev/urandom or /dev/random, which improves performance further: java.security.egd=/dev/random. On my system, this again doubles performance, but the format appears to vary across JVMs.

Finally, I made a modification that constructs a SecureRandom per thread, avoiding synchronization contention, and started to move other methods into Java starting with #hex. This brought about the best performance so far, but I have not committed this change because I'm unsure about saving the SecureRandom per thread and whether that does something "bad" as far as the security of its results.

We need to evaluate all these options and come up with a good balance of security and performance, since it seems that SecureRandom is hit very heavily by frameworks like Rails.

Performance with per-thread SecureRandom and the Java property across JVMs on OS X: https://gist.github.com/headius/8428930

Patch to use a SecureRandom per thread and make #hex native: https://gist.github.com/headius/8429206

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions