Slashdot Mirror


Fixing JavaScript's Broken Random Number Generator (hackaday.com)

szczys writes: It is surprising to learn how broken the JavaScript Random Number Generator has been for the past six years. The problem is compounded by the fact that Node.js uses the same broken Math.random() module. Learning about why this is broken is interesting, but perhaps even more interesting is how the bad code got there in the first place. It seems that a forum thread from way back in 1999 shared two versions of the code. If you read to the end of the thread you got the working version, if you didn't make it that far (perhaps the case with JavaScript devs) you got the bad version of the code whose fix is just now being rolled out.

136 comments

  1. Obligatory XKCD by psergiu · · Score: 4, Informative
    --
    1% APY, No fees, Online Bank https://captl1.co/2uIErYq Don't let your $$$ sit in a no-interest acct.
    1. Re:Obligatory XKCD by antimatter_16 · · Score: 5, Funny
    2. Re:Obligatory XKCD by flubby! · · Score: 0

      "Probably best".
      For what ?
      For whom ?
      If I find Dilbert funny, am I going to be contaminated by its "dumbness" ?
      Are you the ultimate judge of everyone ? Are you the repository of all truth out there ?

      Lighten up.

    3. Re:Obligatory XKCD by Anonymous Coward · · Score: 0

      Jesus christ, did somebody trigger your PTSD again? Or do you just get that turned on by attacking various ideologies?

    4. Re: Obligatory XKCD by Anonymous Coward · · Score: 0

      Things I find ironic, #583:

      Online commentators who take on the task of rooting out those online commentators who take on the task of rooting out online commentators (in the name of social justice)

      Additional conclusion: antisocial hypocrites with a penchant for labeling things, all.

    5. Re: Obligatory XKCD by Anonymous Coward · · Score: 0

      He's a college-educated, whole foods shopping liberal. So, yes. While he'll be brought to tears and inaction by a broken pipe, a flat tire, or an overly friendly squirrel, he is clearly superior and knows what is best for everyone.

    6. Re:Obligatory XKCD by Anonymous Coward · · Score: 0

      You are clearly a jealous little douchebag zero that wants the privelege of losers like you calling you a narcissist!

    7. Re:Obligatory XKCD by Anonymous Coward · · Score: 0

      If it is obligatory, saying so is redundant you fuckstain

    8. Re:Obligatory XKCD by Anonymous Coward · · Score: 0

      SJW's are full of derp and can go die slowly in a fire.

      If Scott Adams called out those losers he should be thanked.

    9. Re:Obligatory XKCD by rubycodez · · Score: 1

      he's a fucking cartoonist; who cares what he thinks? enjoy the fucking cartoons

    10. Re:Obligatory XKCD by Impy+the+Impiuos+Imp · · Score: 1

      Re: both comic authors, a famous quote, "Who would have thought creative types had mental issues?"

      --
      (-1: Post disagrees with my already-settled worldview) is not a valid mod option.
    11. Re: Obligatory XKCD by Anonymous Coward · · Score: 0

      Any adult who intentionally uses the phrase "full of derp" is not worth listening to.

    12. Re: Obligatory XKCD by Anonymous Coward · · Score: 0

      Any person who assumes a person they can't see is an adult is not worth anything.

      Poor little SJW got its panties twisted.

      Die in a fire, slowly.

    13. Re: Obligatory XKCD by Anonymous Coward · · Score: 0

      Grow up, kid.

    14. Re: Obligatory XKCD by Anonymous Coward · · Score: 0

      You should be telling that to the SJW, who obviously need a helmet and padding just to survive the day.

  2. Javascript? lol! by Anonymous Coward · · Score: 4, Insightful

    Is there anything about Javascript that isn't shitty and broken? Can we please just take this language behind the barn, shoot it and move on with our lives?

    1. Re:Javascript? lol! by ickleberry · · Score: 4, Insightful

      We could but all the startup hipsters would be so disappointed

    2. Re:Javascript? lol! by Anonymous Coward · · Score: 0

      JavaScript: the language that proves you can never be too random.

    3. Re:Javascript? lol! by hey! · · Score: 1

      It's support for functional programming?

      --
      Post may contain irony: discontinue use if experiencing mood swings, nausea or elevated blood pressure.
    4. Re:Javascript? lol! by Anonymous Coward · · Score: 1

      You say that like it's a bad thing.

    5. Re:Javascript? lol! by Anonymous Coward · · Score: 0

      No, it is NOT "support for functional programming".

    6. Re:Javascript? lol! by Lunix+Nutcase · · Score: 0

      And how many of the Javascript monkeys actually understand functional programming? A handful?

    7. Re: Javascript? lol! by spectrum- · · Score: 0, Troll

      Well now that Adobe is FINALLY getting rid of Flash, I guess this is the next flawed web technology to hunt down and kill off. It took a long time for html5 to be ready for the task of replacing flash. But what is mature enough and most appropriate to replace JavaScript? And how long will it take the industry to adopt a replacement?

    8. Re:Javascript? lol! by Anonymous Coward · · Score: 0

      Oh, okay. But what about its support for functional programming?

    9. Re:Javascript? lol! by fuzzyfuzzyfungus · · Score: 1

      Its install base?

    10. Re:Javascript? lol! by Anonymous Coward · · Score: 1

      Is there anything about Javascript that isn't sh*tty and broken?

      Amen! It's okay as a light-duty "glue" language, but it's now being used for OS-like features with huge underlying libraries. It's not meant as a systems language. It's outdone Emacs in the over-doing-it department: A tinker-er's paradise, but not practical in the staff churn of everybody business.

      And it has a lousy OOP and inheritance model, forcing one to use annoying and unnatural anonymous functions all over the place.

      The browser stack is turning into an ungainly arcane mess. Great for techie job-security, but if anybody figures out how to clean up or replace the mess, you are out on your bum. Smaller-scale apps that used to be relatively simple to build on desktops now requires DOM rocket science and specialized "framework experts".

      You've been warned.

    11. Re:Javascript? lol! by Anonymous Coward · · Score: 1

      The impressive thing is that you can control the keyboard backlight of a gaming PC with only 20 lines of Javascript. But you need to install about 20 Megabytes of device driver code, USB programming, G++ and Python.

    12. Re: Javascript? lol! by Anonymous Coward · · Score: 1

      HTML5 basically IS Javascript, ya fuckin' dummy. The only thing that's going to replace Javascript is a newer version of Javascript i.e. ECMA6. Javascript, like C++, will just keep getting updated, and so stay relevant forever while the Perls and Rubys will come and Go.

    13. Re:Javascript? lol! by Anonymous Coward · · Score: 0

      Well, prove prototype-based inheritance is objectively better than a good OOP model.

    14. Re:Javascript? lol! by dshk · · Score: 4, Insightful

      We are using JavaScript for performance critical code and I can confirm that it is the most buggiest, immature technology by far that I have ever seen in my 30 years old carrier. Every second month there is a new browser version for each browser, each with a different set of new critical bugs. We even find JIT compiler bugs regularly!

      I simply do not understand why they do not take the free, open source, mature, very fast Java virtual machine, and let the browsers run Java bytecode directly, and let software engineers chose any programming language which best suits their task.

    15. Re: Javascript? lol! by Anonymous Coward · · Score: 0

      You are retarded.

      HTML5 greatly depends on JS,

      Fucking morons

    16. Re: Javascript? lol! by Anonymous Coward · · Score: 0

      Better replace that modem. Impressive carrier!

    17. Re: Javascript? lol! by Anonymous Coward · · Score: 0

      Prove it? How about lurk more for -13 years.

      Prototypes are immensely better in every way: simplicity, parsing, compilation, and most importantly, speed and memory use.
      You get most OOP features basically for 'free' by doing a direct copy, whereas class-based is just a wee bit different, which hits memory more.
      Go look up some benchmarks, then learn how they actually work since you obviously don't know.

      The only downside is JavaScript Prototypes are fucking awfully written and enclosure overhead kills most of its advantages anyway!
      GG JavaScript devs.

    18. Re:Javascript? lol! by Anonymous Coward · · Score: 0

      Maybe because we don't want random developers on the Internet running unverifiable bytecode on our machines with no way to inspect it?

    19. Re: Javascript? lol! by radiumsoup · · Score: 2

      That's like saying, "It's amazing that I can control the ceiling fan in my living room with a $2 light switch, all I had to do was spend $300k building the house first."

    20. Re: Javascript? lol! by Anonymous Coward · · Score: 0

      Ada in the browser, you cretinous chimp! Duh.

    21. Re:Javascript? lol! by Anonymous Coward · · Score: 0

      They'd just move on to Ruby, which is just as hipster as they are.

    22. Re: Javascript? lol! by MachineShedFred · · Score: 2

      A point of information:

      Adobe is killing the Flash brand, but ActionScript lives on. So Flash is not really being killed.

      --
      Slashdot still doesnâ(TM)t support Unicode after it was added to the HTML standard in 1997.
    23. Re: Javascript? lol! by Anonymous Coward · · Score: 0

      In my line work, the coder maintenance effort is usually more of a factor than client-side-browser speed/memory, or even server side for that matter. Whether (good) OOP is inherently more resource intensive than anonymous function prototypes remains to be solidly proven. It may depend on coding style.

      As far "simpler to parse", if that were the main factor, we'd all be using Lisp. Being human-friendly and being machine-friendly are not necessarily the same thing. Machines are generally cheaper than humans (code maintainers) such that economics often favors being human-friendly over machine-friendly (speed/memory). What I personally like is another matter; I'm paid to make my employer's org more efficient. (The database is usually the bottleneck, not the application, I would note.)

      In short, I question how you are weighing the factors being compared. I agree that different niches emphasize different factors, but in general an application language (or usage) should favor humans over machines when you look at the total economics involved. Unfortunately, JavaScript is often being used for application development AND systems software (OS-like services and low-level libraries). One-language-fits-all is a tall order, and probably in impossible order if we want to optimize the language design for its actual usage patterns.

    24. Re: Javascript? lol! by drkstr1 · · Score: 1

      In my line work, the coder maintenance effort is usually more of a factor than client-side-browser speed/memory, or even server side for that matter. Whether (good) OOP is inherently more resource intensive than anonymous function prototypes remains to be solidly proven. It may depend on coding style.

      As far "simpler to parse", if that were the main factor, we'd all be using Lisp. Being human-friendly and being machine-friendly are not necessarily the same thing. Machines are generally cheaper than humans (code maintainers) such that economics often favors being human-friendly over machine-friendly (speed/memory). What I personally like is another matter; I'm paid to make my employer's org more efficient. (The database is usually the bottleneck, not the application, I would note.)

      In short, I question how you are weighing the factors being compared. I agree that different niches emphasize different factors, but in general an application language (or usage) should favor humans over machines when you look at the total economics involved. Unfortunately, JavaScript is often being used for application development AND systems software (OS-like services and low-level libraries). One-language-fits-all is a tall order, and probably in impossible order if we want to optimize the language design for its actual usage patterns.

      I shared this same opinion, but have found protipical inheritance (accompanied with static typing ala closure compiler) to be quite nice. In fact, it has made me more aware of how/when OOP constructs can provid actual value above a more functional approach (hint: it's not as often as you may think)

      --
      Fanboy Status: Apache Flex, C#, Eclipse, KDE, Pirate Party, Ron Paul, Slackware, Windows 7
    25. Re:Javascript? lol! by vel-ex-tech · · Score: 1

      Well, if your only requirement for functional programming is that functions are objects, why not Ruby?

      Generally when I think of functional programming, I think of currying and lazy evaluation. Ruby and Javascript both have neither, but at least Ruby gives you a sane type system and sane scoping rules for anonymous functions. I haven't learned Python yet, but I understand it's in a similar place.

      Well, I should qualify that. I had a hacking session with the person who taught me how to do Javascript correctly. We came up with a way to at least model public and private class members in Javascript. I tried to push the limits to add protected class members, but after a few hours I was like, eh, it's Javascript, whaddaya want?

      The real caveat is with Ruby, since I wonder if I could actually implement parameter currying in Ruby by creating a Class subclass (yes, I've done it before to create a nearly transparent data layer in an experimental hobby project--think Java JPA's @Entity and @Basic annotations but with the Ruby-ism of, instead of declaring an attr_accessor, an attr_persistent) and overriding the method_missing method of Class to emulate currying. Hmm, maybe something to do if my love of programming comes back after I change career to burger flipping.

    26. Re:Javascript? lol! by dshk · · Score: 4, Insightful

      What is the difference between bytecode and obfuscated or simply just complex JavaScript? Do you verify all or even 1% of JavaScript your browser runs? Bytecode can be disassembled into its source language if it is not obfuscated. But JavaScript can be obfuscated as well. Not to mention automatically generated JavaScript, cross compiled from another language. I do not see a difference. Why do you want to verify either bytecode or JavaScript? Bytecode runners wouldn't have more permissions then the JavaScript just in time compilers already have. We rely on the sandboxing in both cases.

    27. Re:Javascript? lol! by AmiMoJo · · Score: 1

      That's kinda what asm.js is. You can use any language you like as long as it compiles down to asm.js, which is stable, well debugged and fast (in theory at least).

      Java is a bit heavy for web apps, and the security model isn't really suitable. Plus, asm.js is much more open and less likely to attract lawsuits.

      --
      const int one = 65536; (Silvermoon, Texture.cs)
      SJW, n: "Someone I don't like, and by the way I'm a fuckwit" - AC
    28. Re: Javascript? lol! by Anonymous Coward · · Score: 0

      Do you have some realistic examples?

      Also, approach-ability by "random" developers sometimes trumps something that's more flexible but requires more experience or a learning curve. Staff changes such that we often have to target "middle brow" abstractions.

    29. Re:Javascript? lol! by dshk · · Score: 1

      We tested asm.js a year ago, it is not particularly fast even within the JavaScript universe (i.e. it was much slower than other JavaScript solutions we have found). And of course browser variants/versions (even small versions!) seriously differ - but that would not be a showstopper, as that can be said about anything in JavaScipt.

      Of course they can slowly fix everything in JavaScript, make it more performant, and eventually reach the current level of the Java virtual machine - in about 10-15 years. This is what I expect.

      The security model is more related to the class library, not to the virtual machine. Like Android uses Java byte code, but an entirely different security model.

      Lawsuits would be a problem, but I guess Oracle would agree on the terms of standardization.

    30. Re:Javascript? lol! by Anonymous Coward · · Score: 0

      This is the best criticism you can offer? Why not talk about how Lisp coders are often shit imperative programmers? Or how Java "monkeys" are often shit Javascript programmers? I've lived through the ivory tower myself and haven't seen such a high-headed attitude as I do on sites like Slashdot. "Wah, a programming language used by people of all skill levels has people who don't know how to program as well as I wish they could!'

    31. Re:Javascript? lol! by drkstr1 · · Score: 1

      Check out underscorejs for a great example of functional programming in javascript, and curry away to your heart's content.

      --
      Fanboy Status: Apache Flex, C#, Eclipse, KDE, Pirate Party, Ron Paul, Slackware, Windows 7
    32. Re: Javascript? lol! by drkstr1 · · Score: 1

      Do you have some realistic examples?

      Also, approach-ability by "random" developers sometimes trumps something that's more flexible but requires more experience or a learning curve. Staff changes such that we often have to target "middle brow" abstractions.

      Sure, since you asked... I find that functional programming is better for processing "data," while OOP is better for processing/handling "events." I also think there is a line that can be crossed where functional programming simply becomes a clever form of obfuscation, but overall, there is a lot of value in simple, repeatable, and easy to use constructs, which may be composed together to express the "idea" behind the code in fewer lines. I would say that readability and maintainability ranks #1 in my book of priorities, and functional programming helps very well with this in a lot of cases. Underscorejs is a good example of FP in javascript, if you're unfamiliar.

      --
      Fanboy Status: Apache Flex, C#, Eclipse, KDE, Pirate Party, Ron Paul, Slackware, Windows 7
    33. Re:Javascript? lol! by drkstr1 · · Score: 1

      We are using JavaScript for performance critical code and I can confirm that it is the most buggiest, immature technology by far that I have ever seen in my 30 years old carrier. Every second month there is a new browser version for each browser, each with a different set of new critical bugs. We even find JIT compiler bugs regularly!

      I simply do not understand why they do not take the free, open source, mature, very fast Java virtual machine, and let the browsers run Java bytecode directly, and let software engineers chose any programming language which best suits their task.

      Not to come across sounding like "you're doing it wrong," but I found I had a fairly similar experience when I needed to produce some solid javascript (rather intensive real-time media/graphics in mobile web). It wasn't until I realized I was trying to hammer a screw (applying my knowledge of c/c++/Java/C# to my JavaScript code) that my experiences turned around. In short, a relatively small amount of your code should be exposed to browser specific bugs, to the point where most of it can be tested without any browser at all. This makes the browser bugs easy to plan for, and code around as if routine (the unstable bits are fairly well known at this point, I would say). I would suggest getting you some static typing with either TypeScript or the closure complier (I have only had experience with the later, to great results). Then get you some JavaScript Design Patterns, and some Functional JavaScript, and you are all set. Cheers and good luck!

      --
      Fanboy Status: Apache Flex, C#, Eclipse, KDE, Pirate Party, Ron Paul, Slackware, Windows 7
    34. Re:Javascript? lol! by Anonymous Coward · · Score: 0

      Is there anything about Javascript that isn't shitty and broken? Can we please just take this language behind the barn, shoot it and move on with our lives?

      No.

      It will continue to evolve into a "real" language. The fact is it is everywhere and everyone that wants to make a replacement and has the means to push it out has their own motives for doing so entirely unrelated to performance, scaleability, security or portability (especially portability.) JavaScript won the "most supported in a browser" title and the "easiest to use for a novice" title making it the ideal choice for pretty much everything because programmers are the only ones that really care about elegance in any of the aforementioned areas (at least in any practical sense.)

      Frankly at this stage I'd rather just see them start making JavaScript engines in everything - kernels for desktop, server and embedded systems so it can run natively a bit faster. It's all headed that way anyway and the only other option given "how to get better from where we are now" is to continue piecemealing everything.

    35. Re: Javascript? lol! by Tablizer · · Score: 1

      Underscorejs seems to be reinventing SQL with dots: rows = dataSource.join(...).select(...).where(...).orderby(...);

    36. Re:Javascript? lol! by Anonymous Coward · · Score: 0

      You can add lazy evaluation to Ruby.

      Rails did it with ActiveRecord.

      There is little that you can not add to Ruby.

    37. Re:Javascript? lol! by Anonymous Coward · · Score: 0

      The security model is not related to either the JVM or the class library. smh

      V8 can run faster than the JVM, if the programmer knows JS well enough.

      asm.js can take C code compiled down to asm.js and its performance is well within an order of magnitude(less than half of that in some cases) of that C code compiled with a C compiler, that is more than fast enough for any reasonable use of JS..

    38. Re:Javascript? lol! by Jonner · · Score: 1

      Is there anything about Javascript that isn't shitty and broken? Can we please just take this language behind the barn, shoot it and move on with our lives?

      As terrible as the language called "Javascript" may be, this isn't an example of that. It's an example of a poor implementation of one standard library function in one implementation of the language. It seems the problem was fairly easily fixed. Javascript code doesn't need to be changed to use the better PRNG so it would be very foolish to abandon Javascript just because of the past poor PRNG.

    39. Re:Javascript? lol! by Anonymous Coward · · Score: 0

      Censoring quotes makes you a fucking piece of shit retard.

      Geez, maybe the Internet is too scary for you.

    40. Re:Javascript? lol! by Anonymous Coward · · Score: 0

      I simply do not understand why they do not take the free, open source, mature, very fast Java virtual machine, and let the browsers run Java bytecode directly, and let software engineers chose any programming language which best suits their task.

      I guess you don't pay attention to Java applet security alerts. There are about 100 a week.

      JS is actually far more secure.

  3. Obligatory dilbert by Anonymous Coward · · Score: 0

    http://dilbert.com/strip/2001-10-25

  4. Wait, what? by tibit · · Score: 5, Insightful

    What? Does the ECMA spec dictate the exact implementation of the RNG? If not, then it's not JavaScript that's broken, but the implementation(s) in question. Calling it "JavaScript's Broken RNG" is nonsense unless the language spec mandated or mandates a broken RNG.

    --
    A successful API design takes a mixture of software design and pedagogy.
    1. Re:Wait, what? by Anonymous Coward · · Score: 5, Informative

      Blame slashdot. TFA's made it pretty clear it's the V8 engine that had been broken for six years.

    2. Re:Wait, what? by Lunix+Nutcase · · Score: 5, Insightful

      Yeah, seems rather convenient that the part in the Hackaday title and in the article that mentions that this was in Google's V8 engine was left out.

      Plus I couldn't help but laugh at the comment to the commit that put in this shitty PRNG:

      This is great, I had talked to Ivan once about it before. It's good that we avoid system random for a few reasons, including thread safety / lock holding / etc.

      I know nothing of the implementation though, I would have gone with mersenne twister since it is what everyone else uses (python, ruby, etc)

      Sounds like some real quality code reviewing there, bub. *golf clap*

    3. Re:Wait, what? by Anonymous Coward · · Score: 0, Insightful

      You're reading a blog for foolish, angry reactionaries who like to pretend to be smart people. What did you expect? Had you been away for years?

    4. Re:Wait, what? by Anonymous Coward · · Score: 1

      That's just tragic. The reviewer is familiar enough with PRNGs to mention the mersenne twister, but blindly accepted a goofy PRNG implementation. Even smart people are lazy and stupid some of the time.

    5. Re:Wait, what? by Lunix+Nutcase · · Score: 1

      Yeah, might as well have had no code review at all.

    6. Re:Wait, what? by Anonymous Coward · · Score: 0

      Maybe Google should stop exclusively hiring "top five school" dipshits who are "ace students" but weak geeks.

    7. Re:Wait, what? by Lunix+Nutcase · · Score: 4, Interesting

      Well at least knowing that the guy who wrote this shitty PRNG is a designer of Google's Dart gives you one more reason to avoid it the plague.

    8. Re:Wait, what? by BarbaraHudson · · Score: 2
      The situation in example given in the article could have been avoided entirely if it had been done right:

      to assign per-session tokens to users. They thought they were fine, because the chances of a collision were vanishingly small if the PRNG was doing its job.

      How stupid do you have to be to use any value as a "unique" token without verifying that it is not currently in use? Even truly random numbers will still have the rare collision. In other words, "vanishingly small" != unique.

      --
      "Transparent" is a shit show that trades on every stereotype going. A man in drag is NOT a transsexual.
    9. Re:Wait, what? by Lunix+Nutcase · · Score: 1

      Yeah, seems one would have chosen a UUID generator not a PRNG.

    10. Re:Wait, what? by Anonymous Coward · · Score: 2, Informative

      TFA isn't that good either though. It spends the first half of the page with patronising pedantry about how numbers cannot be random, which is a waste of time since ‘random’ can mean ‘randomly chosen’. Here, I'll have a go at summarising the situation.

      V8's random number generator is pretty bad. It's a thing called MWC1616, which basically means it's two multiply with carry random number generators, of whose outputs the lower 16-bits are concatenated to form a single 32-bit number. MWC generators aren't particularly good; they're related to linear congruential generators. But sticking two together could improve the cycle length, as long as the cycles are different. But due to the fact that MWC1616 sticks two 16-bits numbers together, the most significant bits just have the short cycle length. That's a problem, because in many random number applications the most significant bits tend to be more... eh... significant. Examples include the use of multiply-and-floor to roll dice (d = floor(rnd * 6)) or when the number gets used straight-up in physical simulations. So the effective cycle of MWC1616 is pretty short.

      There's an interesting lesson here, by the way, as the original author of the algorithm could have known about this problem if he had thought his method of combining the generators through, but ‘the algorithm passed all tests’ so it was good. I too often see code that passes unit-tests but that's nevertheless deeply flawed, so please, people, if you've only got time to either write unit tests or think, then please, please think - it's more important. Later, the author did think about it, and did realise his mistake and published a different version, but the original got published in various places, including on Wikipedia. And hey, it's on Wikipedia, and it has a cited source, so it must be good, right?

      The fact that MWC1616 was an odd choice was picked up during code review. The reviewer noted the odd choice saying ‘I would have gone with mersenne twister’ but the algorithm wasn't changed or investigated. The warning was raised, but not acted upon. Another important lesson: if you have code review, use the results, otherwise it's pointless busywork.

      So, did the V8 random number generator get replaced by the Mersenne twister? No, they opted to use XorShift128+, presumably because it's slightly faster and uses a lot less memory, while still passing common randomness tests. But I have my reservations about this decision. The Mersenne twister is fast enough, well-understood, hard to misuse and has a long cycle-length. XorShift is by the same author as MWC1616 and relatively unknown, so there's (in my view) a bigger chance that it contains some bigger as-yet undiscovered hidden flaw.

    11. Re:Wait, what? by Anonymous Coward · · Score: 0

      Of course, I tried to correct the Wikipedia article, but it got reverted without explanation within the hour.

    12. Re:Wait, what? by AmiMoJo · · Score: 1

      Sadly this is industry standard practice. For example, Microsoft GUIDs are used extensively and are just randomly generated numbers. At least they are usually 64+ bits, but some are still 32 bit.

      The problem is that it works and collisions are so rare they don't become a cost for the developers. The fix would require creating infrastructure to hand out GUIDs, and it's always hard to justify spending time and money developing a secure system to do that (GUIDs must not be predictable) when there is no visible problem.

      --
      const int one = 65536; (Silvermoon, Texture.cs)
      SJW, n: "Someone I don't like, and by the way I'm a fuckwit" - AC
    13. Re:Wait, what? by AmiMoJo · · Score: 2

      Actually, you just embarrassed yourself. The function spec says that the numbers produced don't have to be cryptographically secure, so his implementation is absolutely fine. It produces pseudo random numbers quickly. If you want secure the docs say use something else.

      This fix is more like fixing the stupidity of programmers who, like you, didn't RTFM and used this function for security related tasks.

      --
      const int one = 65536; (Silvermoon, Texture.cs)
      SJW, n: "Someone I don't like, and by the way I'm a fuckwit" - AC
    14. Re:Wait, what? by fnj · · Score: 2

      For example, Microsoft GUIDs are used extensively and are just randomly generated numbers. At least they are usually 64+ bits, but some are still 32 bit.

      GUIDs are 128 bits, of which 122 bits may be either pseudo random or made up using such input as MAC address and time.

    15. Re:Wait, what? by Lunix+Nutcase · · Score: 1

      Teah I'm so embarrassed because some guy wrote a shit PRNG. Oh how will I ever live with myself. /s

    16. Re:Wait, what? by Anonymous Coward · · Score: 0

      NSA.

    17. Re:Wait, what? by Alioth · · Score: 1

      There are plenty of reasons why you might not verify a particular token is in use. For instance, we have a system which is highly distributed for which checking token uniqueness would be very costly (both to implement and at runtime). It uses version 4 UUIDs as an identifier (122 bit random), which is about 5.3x10^36 possible combinations.

      You'd have to generate one of these every millisecond for tens of millions of years to even get to even a 50% chance of picking the same random UUID twice, given a good RNG. It's simply not worth adding the complexity to a distributed system to check for duplicates with those kinds of odds.

    18. Re:Wait, what? by BarbaraHudson · · Score: 1
      The solution to that is very simple - whichever system is called upon to generate the token is the one that throws out any token that doesn't meet additional rules. If it's system A, throw out every token that begins with a '1'. If it's system B, 'throw out any token that begins with a '2'. This way you also know which system to check to verify the token.

      An additional benefit is that is a token that was generated in the area served by 'A' suddenly appears in an area served by 'B', you may want to code in checks to see if this was because the token was hijacked. You can't do that if you rely solely on generating unique tokens and not storing them anywhere until they (or the session) expires.

      --
      "Transparent" is a shit show that trades on every stereotype going. A man in drag is NOT a transsexual.
  5. Obviously by penguinoid · · Score: 2

    What did you expect from some random coder?

    --
    Don't waste your vote! Vote for whoever you want, unless you live in a swing state it won't matter anyways
    1. Re:Obviously by Lunix+Nutcase · · Score: 1

      No random coder. A guy employed by Google and now working on Dart. One can only hope that he hasn't touched anything else related to PRNGs, cryptography, etc. since he wrote this broken code 7 years ago.

    2. Re:Obviously by Lennie · · Score: 5, Interesting

      He was using node.js (which using V8 Javascript engine)

      And he was using it for some security related function (in this case generating id's of sessions).

      Maybe he should have been using a cryptographically strong pseudo-random generator:
      https://nodejs.org/api/crypto....

      Why did they need to 'fix' V8 Math.random () function which everyone knows is not meant for such things ? It even says so in for example the Mozilla documentation (the organisation that created Javascript in the first place):
      "Note: Math.random() does not provide cryptographically secure random numbers. Do not use them for anything related to security."
      https://developer.mozilla.org/...

      This makes no sense to me.

      --
      New things are always on the horizon
    3. Re:Obviously by Lunix+Nutcase · · Score: 1

      You're confusing two different people from the article. The person who checked-in the broken PRNG code was a Google employee named Kasper Lund. The person who found the bug when they were using the class to generate session ids was Mike Malone.

    4. Re:Obviously by Lunix+Nutcase · · Score: 1

      And to clarify, my original post was about the Google employee who broke V8's random number generator.

    5. Re:Obviously by Anonymous Coward · · Score: 0

      More to the point, a random script kiddie.

    6. Re:Obviously by Anonymous Coward · · Score: 0

      Kasper Lund? That's a made up name by someone who speaks Hindi as a native language.

    7. Re:Obviously by Anonymous Coward · · Score: 0

      Vesper Lynd was a femme fatale in Casino Royale.

    8. Re:Obviously by swillden · · Score: 1

      One can only hope that he hasn't touched anything else related to PRNGs, cryptography, etc. since he wrote this broken code 7 years ago.

      I'm not sure why you mentioned "cryptography, etc.", since Math.random() should never be used for cryptography or other security purposes. It's entirely reasonable to believe that if it were supposed to be used for those purposes that the Google engineer would have picked something known to be good for those purposes.

      --
      Note to ACs: I usually delete AC replies without reading them. If you want to talk to me, log in.
    9. Re: Obviously by Anonymous Coward · · Score: 0

      Eh? Seems a perfectly normal Scandinavian name to me.

  6. V8 == the only JavaScript engine? by BitZtream · · Score: 4, Insightful

    Because JavaScript doesn't specify the RNG implementation details, and V8 is the only engine mentioned ass affected in the article ...

    --
    Persistent Volume manager for Kubernetes - https://github.com/dwimsey/openshift-pvmanager
  7. Obligatory v.Neumann: SIN ! by redelm · · Score: 2

    "Any one who considers arithmetical methods of producing random digits is, of course, in a state of sin. For, as has been pointed out several times, there is no such thing as a random number - there are only methods to produce random numbers, and a strict arithmetic procedure of course is not such a method." John von Neumann

    That said, even JvN understood the usefulness of pseudo random numbers for things like Monte Carlo simulations. I believe he favored Linear Congurential Generators (Knuth liked 69069 as a multiplicand on a 32-bit word).

  8. It was noticed at least 3 years ago, possibly more by Anonymous Coward · · Score: 0

    This stack exchange post is 3+ years old. Why does the article claim this is new information that Math.random() can't be relied on for the entropy it claims to produce?

    https://security.stackexchange.com/questions/20029/generate-cryptographically-strong-pseudorandom-numbers-in-javascript

  9. And StackOverflow didn't even exist! by jtara · · Score: 1

    It seems that a forum thread from way back in 1999 shared two versions of the code. If you read to the end of the thread you got the working version

  10. Re:It was noticed at least 3 years ago, possibly m by Lunix+Nutcase · · Score: 4, Informative

    The article doesn't claim it's new information. The article is about the fact that Google has finally fixed it and the backstory behind the broken code.

  11. Oh yeah? by U2xhc2hkb3QgU3Vja3M · · Score: 3, Funny

    Well if you don't like RNG you should try WHM, BML or THF.

  12. More code audits needed? by Lunix+Nutcase · · Score: 2

    So now that we know it's Kasper Lund who broke this within the V8 engine, is someone going to do a code audit of all checkins he's done within the Dart SDK to make sure he hasn't broken anything related to PRNGs and cryptography?

    1. Re:More code audits needed? by U2xhc2hkb3QgU3Vja3M · · Score: 3, Funny

      What would be the point of wasting time fixing something that nobody uses?

    2. Re:More code audits needed? by dfsmith · · Score: 1

      The spec only says "approximately uniform". The code generated approximately uniform numbers, for some value of approximate, so it wasn't broken per se.

    3. Re:More code audits needed? by Lunix+Nutcase · · Score: 2

      Sure, it's only broken when actually used.

    4. Re:More code audits needed? by Anonymous Coward · · Score: 0

      No, only broken when used out of specification.
      RNGs have a lot of uses, not all of them related to cryptography. Generators suited for cryptography could be extremely unsuitable for other uses.
      Take for example the ISO-C random function. It is specified for reproducibility. There is even a non-mandatory recommendation to because they saw a use for a generator that behaved the same way on a variety of systems, for example when implementing sprite behavior in games.

      If you implement cryptography and uses a RNG that isn't specified for it then it is your code that is broken. It's like using a CRC designed for sequential data when communicating over a framed protocol like RS485.
      It isn't the one implementing the CRC that is to blame, it is the one who applied it incorrectly.

    5. Re:More code audits needed? by Anonymous Coward · · Score: 0

      An example of this is machine learning. Uniformly Random is important to avoid learning the bias of dataset, but correlations don't matter very much unless the correlated variable is an input of the dataset.

    6. Re: More code audits needed? by Anonymous Coward · · Score: 0

      You got some personal vendetta against this guy? Jeez, get over it.

    7. Re:More code audits needed? by Anonymous Coward · · Score: 0

      No, only broken when used out of specification. RNGs have a lot of uses, not all of them related to cryptography. Generators suited for cryptography could be extremely unsuitable for other uses. Take for example the ISO-C random function. It is specified for reproducibility. There is even a non-mandatory recommendation to because they saw a use for a generator that behaved the same way on a variety of systems, for example when implementing sprite behavior in games.

      If you implement cryptography and uses a RNG that isn't specified for it then it is your code that is broken. It's like using a CRC designed for sequential data when communicating over a framed protocol like RS485. It isn't the one implementing the CRC that is to blame, it is the one who applied it incorrectly.

      ..Quoting AC rated at 0 as the only reasonable response to this thread..

    8. Re:More code audits needed? by drkstr1 · · Score: 1

      No, only broken when used out of specification. RNGs have a lot of uses, not all of them related to cryptography. Generators suited for cryptography could be extremely unsuitable for other uses. Take for example the ISO-C random function. It is specified for reproducibility. There is even a non-mandatory recommendation to because they saw a use for a generator that behaved the same way on a variety of systems, for example when implementing sprite behavior in games.

      If you implement cryptography and uses a RNG that isn't specified for it then it is your code that is broken. It's like using a CRC designed for sequential data when communicating over a framed protocol like RS485. It isn't the one implementing the CRC that is to blame, it is the one who applied it incorrectly.

      ..Quoting AC rated at 0 as the only reasonable response to this thread.. (Try 2 haha, oops)

      --
      Fanboy Status: Apache Flex, C#, Eclipse, KDE, Pirate Party, Ron Paul, Slackware, Windows 7
  13. Happened, not designed. by QuietLagoon · · Score: 3, Insightful

    JavaScript was not designed by any regular use of that word. JavaScript happened.

    1. Re:Happened, not designed. by Anonymous Coward · · Score: 0

      Underrated post.

    2. Re:Happened, not designed. by Anonymous Coward · · Score: 1

      You are confusing PHP with Javascript.

      JS has a very powerful and sane subset.

      PHP does not.

    3. Re:Happened, not designed. by QuietLagoon · · Score: 1

      You are confusing PHP with Javascript.

      I am aware of both PHP and JavaScript. I said nothing about PHP. My opinion about Javascript is my opinion about Javascript, not PHP. I do not confuse the two.

      .
      JavaScript happened, it was not designed.

    4. Re:Happened, not designed. by Anonymous Coward · · Score: 0

      Javascript happened, but there's still time to stop it from continuing to happen...

    5. Re:Happened, not designed. by Anonymous Coward · · Score: 0

      Unlike PHP, JS has some very good design, mixed in with awful design, none of which has to be used.

      PHP has awful design throughout the language and is impossible to avoid.

  14. WebCrypto by Anonymous Coward · · Score: 0

    It has PRNG at window.crypto.getRandomValues

    per http://stackoverflow.com/questions/5651789

  15. ISAAC.js by Anonymous Coward · · Score: 0

    Jenkins created a very fast secure random number generator in 1996.

    https://github.com/rubycon/isaac.js

  16. The damned librals everywhere! by 140Mandak262Jamuna · · Score: 1
    Why can't they leave at least one bastion of free enterprise and perfect competition? Why should they come in ask for equal representation of every 32 bit patterns? These numbers should know that in America every one gets equal opportunity not equal outcomes. It is a tough world out there and you have 32 bits and the other number has 32 bits. Fight your way and get represented as often as you can or fall by the way side.

    We should carve out an exception for the sincerely held religious beliefs to serve or not serve any particular random number for the generator.

    --
    sed -e 's/Chuck Norris/Rajnikant/g' joke > fact
  17. That's why JS is untyped then... by sugar+and+acid · · Score: 1

    That's why JS is untyped, it adds much needed randomness.

  18. Seeds are important. by BarbaraHudson · · Score: 1

    Since seed values are important, why not just use the comments in slashdot - some of them are REALLY random.

    Or use the latest presidential campaign statements - can't get much more random than that (for some definitions of random).

    --
    "Transparent" is a shit show that trades on every stereotype going. A man in drag is NOT a transsexual.
    1. Re:Seeds are important. by Anonymous Coward · · Score: 0

      Because repetitive.

  19. ibm comes to mind by Anonymous Coward · · Score: 0

    whatever mistake you make, ibm was there usually before you :)

    IIRC they selected constants in their LCG in such manner so that it would play nicely with the hardware in order to have fast generator that was good enough.
    It may have been fast, but it fails the spectral test big time: if you look up RANDU on internet you'll see that it does not distribute numbers uniformly, but they "stay mainly in the planes":
    http://random.mat.sbg.ac.at/results/karl/server/node4.html#randu

  20. Fixing *Google's* random number generator by AC-x · · Score: 1

    This is fixing Google's random number generator; Firefox, Safari and MS Edge (if not old IE versions) have never had this issue, it is specific to Google's JS implementation.

  21. Random functions... by Kazoo+the+Clown · · Score: 3, Informative

    I've seen some pretty bad "random number" generators in my time. In one case, it was implemented by a pointer that would walk through the processes memory space and use whatever it found as-is. And another where the coder clearly thought that if you multiply something by enough made up crap and take the remainder, you get randomness. An understanding of random numbers in computing is not something the classrooms ever cover as far as I can tell.

    1. Re:Random functions... by Anonymous Coward · · Score: 0

      This was my most hilarious:

      static int seed; //do not initialise to enhance randomness

  22. Every browser since IE10 has had secure RNG by Scorpinox · · Score: 3, Informative

    See this table for support: http://caniuse.com/#feat=getra...

    It's great that they're finally improving Math.random(), but node.js should've had crypto.getRandomValues() from the start.

  23. Ignorance is bliss by Anonymous Coward · · Score: 1

    Given there is no way to seed math.random assumptions about collisions are meritless and storage of random identifiers in databases serves no useful purpose other than causing needless index fragmentation.

    In short TFA while having a point about quality of a specific implementation of math.random() is bitching about things that could still be failures even if math.random() represented an ideal PRNG.

    Also hardware random number generators are what you get for free when you sleep through your 101 class on noise margins. Invoking the normal exotic bullshit about computation and radioactively decay is completely unnecessary. Good old thermal noise is what most hardware random number generators use and is as nondeterministic as any "quantum" outcome.

  24. Doesn't this just affect Chrome? by Mr+Z · · Score: 1

    Seems like this should just affect Chrome / Chromium and anything derived from those, as it's an implementation issue in the V8 JavaScript interpreter. (V8 is the name for the engine in Chrome.)

    That is, it's not a JavaScript / ECMAScript bug in the standard (as implied by the headline), but rather a bug in one company's implementation.

    Compare/contrast with the comically bad PRNG enshrined in the C standard itself:

    static unsigned long int next = 1;
    int rand(void) // RAND_MAX assumed to be 32767
    {
    next = next * 1103515245 + 12345;
    return (unsigned int)(next/65536) % 32768;
    }

    Thankfully, though, this is just an example, and not required by the standard. But, many simple C compilers use that implementation. It's got plenty of problems, such as always alternating between even and odd values. If the last value was odd, the next value is even....

  25. The mighty Knuth by ICantFindADecentNick · · Score: 1

    Knuth covers this definitively in Volume 2 of "The Art of Computer Programming". I think I first read it in 1979 so it certainly used to be covered in teaching, maybe that's all been lost in the later generations. Now get off my lawn.

    1. Re:The mighty Knuth by Kazoo+the+Clown · · Score: 1

      It's not clear Knuth was used all that much even back then, and I wonder if it's been in use at all in the last 20 years or so.

    2. Re:The mighty Knuth by Anonymous Coward · · Score: 0

      You may be right - but your description of the "gather the crap" algorithms so strongly reminded me of Knuth's discussion of Algorithm "K" which means that he had already learned what the authors of those bad algorithms were going to do years later. Maybe he should be studied a bit more?

      For those not familiar with it:

      "It is not easy to invent a foolproof source of random numbers. This fact was convincingly impressed upon the author in 1959, when he attempted to create a fantastically good generator using the following peculiar approach:

      Algorithm K (“Super-random” number generator). Given a 10-digit decimal number X, this algorithm may be used to change X to the number that should come next in a supposedly random sequence. Although the algorithm might be expected to yield quite a random sequence, reasons given below show that it is not, in fact, very good at all. (The reader need not study this algorithm in great detail except to observe how complicated it is; note, in particular, steps K1 and K2.)

      K1. [Choose number of iterations.] Set Y X/109, the most significant digit of X. (We will execute steps K2 through K13 exactly Y + 1 times; that is, we will apply randomizing transformations a random number of times.)
      K2. [Choose random step.] Set Z X/108 mod 10, the second most significant digit of X. Go to step K(3 + Z). (That is, we now jump to a random step in the program.)
      K3. [Ensure 5 × 109.] If X 0, decrease Y by 1 and return to step K2. If Y = 0, the algorithm terminates with X as the desired “random” value."

      The machine-language program corresponding to this algorithm was intended to be so complicated that a person reading a listing of it without explanatory comments wouldn’t know what the program was doing.)

      Considering all the contortions of Algorithm K, doesn’t it seem plausible that it should produce almost an infinite supply of unbelievably random numbers? No! In fact, when this algorithm was first put onto a computer, it almost immediately converged to the 10-digit value 6065038420, which—by extraordinary coincidence—is transformed into itself by the algorithm (see Table 1). With another starting number, the sequence began to repeat after 7401 values, in a cyclic period of length 3178.

      The moral of this story is that random numbers should not be generated with a method chosen at random. Some theory should be used."

  26. Why didn't they optimize the new generator? by Terje+Mathisen · · Score: 1

    The new 128-bit generator is shown as this piece of code, using a pair of 64-bit state variables:

    uint64_t state0 = 1;
    uint64_t state1 = 2;
    uint64_t xorshift128plus() {
        uint64_t s1 = state0;
        uint64_t s0 = state1;
        state0 = s0;
        s1 ^= s1 > 17;
        s1 ^= s0;
        s1 ^= s0 >> 26;
        state1 = s1;
    }

    The absolute minimum latency of that code is 8 clock cycles, assuming that the two initial loads happen at the same time and that the writeback of s1 to state1 is overlapped with the return, i.e. free.

    It seems like an obvious optimization to notice that s0 could be updated in parallel with the two initial s1 updates, i.e.

        s1 ^= s0;
        s1 ^= s0 >> 26;

    can instead be written as

        s0 ^= s0 >> 26; // These two clock cycles can be overlapped with the previous s1 updates!
        s1 ^= s0;

    since we don't care about the s0 value after this point and XOR operations are commutative (it is of course possible that the compiler is smart enough to do the same optimization, but I doubt it):

    This is two clock cycles faster than the original code.

    Terje

    --
    "almost all programming can be viewed as an exercise in caching"
    1. Re:Why didn't they optimize the new generator? by TangoMargarine · · Score: 1

      Are we really still in an era where we care about counting individual clock cycles, outside of an embedded context?

      --
      Unity? Screw that: XFCE. Slashdot Beta? Screw that: SoylentNews. Australis? Screw that: Pale Moon. UX developers DIAF
    2. Re:Why didn't they optimize the new generator? by Anonymous Coward · · Score: 0

      Yes

      Using a cryptographically secure RNG in contexts where it doesn't matter slows things way down.

      Even a simple dice-rolling game such as Yahtzee becomes noticeably slow when using a cryto quality RNG.

    3. Re:Why didn't they optimize the new generator? by Anonymous Coward · · Score: 0

      Especially since we're talking about A) JavaScript in browsers, which apparently people think "more is better", and B) a library that isn't crypto-quality to begin with.

      (fucking /. being an asshole about logging in still I see -tm)

  27. No surprise though by Anonymous Coward · · Score: 0

    Most RNGs are shit, and all of javascript is shit. That javascript's RNG is shitty^2 is simple math.

  28. Huh? by Hognoxious · · Score: 1

    I thought it was axiomatic that the inbuilt default PRNG was good for writing scissors/paper/stone when doing programming 101 but not for anything more serious.

    In any language.

    --
    Confucius say, "Find worm in apple - bad. Find half a worm - worse."
  29. Re:Javascript? lol! [server-bound] by Tablizer · · Score: 1

    The more of an application you do server-side, in a language of your choosing, the less you have to depend on browser JavaScript (and other browser issues). But, it takes experience to do that well. One cannot think in "desktop mode" anymore, and toss much of their desktop UI design experience. It's bummer, but it's what the Web Stack forces on us if we want to avoid JavaScript and client-versioning headaches.