• A Nonny Mouse (unregistered)

    i like these in particular

                                } // end for
                            } // end if hash_bytes
                        } // end if val non null
                    } // end if key non null
                } // end while e.hasMoreElements

     so THAT's what }'s do...!

  • mustache (unregistered)

    "The function, getRandomBIts() returns a 32-yte array of random bites for security purposes."

    BIts?  ytes?  bites?  Make your mind up...

    Still, good to see the CodeSOD back. 


    Edit by MC: Err, whoops. my B key doesn't work so well, and I missed that -_-;. Fixed now.

  • Anonymous (unregistered)

    What an innovative way to do it! I bet he got paid by the line.

  • (cs)

    Makes you wonder how Random.nextBytes() is implemented.

  • Kyuzo (unregistered)

    This is definitely the hallmark of a good WTF...code that is twenty times more complex and introduces many new points of failure, while not being any more secure since it adds practically no entropy to the random data.

  • (cs) in reply to Kyuzo
    Anonymous:

    This is definitely the hallmark of a good WTF...code that is twenty times more complex and introduces many new points of failure, while not being any more secure since it adds practically no entropy to the random data.


    When I was going through the queue, it was the one that jumped out at me, because the guy knows how to do things like read Java configurations, but doesn't know Random(). I also find it funny how short the non-WTF version is.
  • (cs)

    Although it doesn't make this any less of a WTF, I suspect the author was really trying to generate a GUID based on the fact that he was incorporating the system properties. The idea being to get a random sequence that was unique to the machine.

  • (cs)

    Wow!  Knuth's going to have to add a new section to his chapter on random numbers.

  • (cs) in reply to limelight
    limelight:
    Although it doesn't make this any less of a WTF, I suspect the author was really trying to generate a GUID based on the fact that he was incorporating the system properties. The idea being to get a random sequence that was unique to the machine.

    It's been awhile since I touched Java, but at least on Win32, isn't there a direct API for generating GUIDs?

  • Gordonious (unregistered)

    Oh, didn't you know? That's how the Java Random class is implemented internally anyway!

  • Moosey (unregistered)

    "Without further to do"?!  Jesus.  This site alone could be fodder for a linguistic WTF blog.

     

  • (cs) in reply to Gordonious
    Anonymous:
    Oh, didn't you know? That's how the Java Random class is implemented internally anyway!

    Well, Java is now open source, maybe I should look through the Random class code. Perpahs there is another WTF to be found there ;-).

  • (cs) in reply to A Nonny Mouse
    Anonymous:

    i like these in particular

                                } // end for
                            } // end if hash_bytes
                        } // end if val non null
                    } // end if key non null
                } // end while e.hasMoreElements

     so THAT's what }'s do...!

    Actually - I do some similar myself as it often helps my overview of the indentation, rather then having to trace an ending scope up to the starting point.

     

  • (cs)
    Michael Casadevall:

    The function, getRandomBits() returns a 32-byte array of random bites for security purposes. Since Java provides a Random method, this should be easy...

    If this is in fact "for security purposes", then using Java's Random method would be as equally WTFy (and the five-line implementation is no more "correct" than the long one).

    There is no "correct" way to generate pseudorandom data.  That's a domain-dependent function; the PRNG has to meet the particular requirements of the task.  In this case, of course, we have no information on those requirements other than "for security purposes", but if that's at all accurate we have some reason to believe that Java's Random would be quite wrong as well.

    I rarely use Java, so my docs are well out of date, but I note that there at least used to be a java.security.SecureRandom, which at least claims to be suitable for some security purposes.

    But what this item shows is that security code shouldn't be written by non-experts - and that's so well established it can hardly be counted a WTF.

     

  • (cs)

    Actually, the real WTF is both the "custom" random, and the suggestion to use the non-secure Random class for security purposes.

     

    There is a standard class designed for secure random number generation, which is far more secure than MD4ing a bunch of somewhat predictable values. 

    http://java.sun.com/j2se/1.4.2/docs/api/java/security/SecureRandom.html

  • Eli (unregistered) in reply to limelight

    I don't think the author was going for a GUID. Yes, it's based on some values that are related to that particular system, but there's certainly no guarantee that the number is globally unique. You'd get just as good a GUID from plain old Random(). Face it, this is just a very poor implementation of a psuedo random number generator.

    My favorite part is the bit where it eats the exception for grabbing system data. So... if something goes wrong, it will just silently hash the system clock? Awesome.

  • (cs)

    This is the trouble with java programming books.  They talk all about sorts, arrays, etc. and so people think that you have to use sorts and arrays at all times.  Someone should really come up with a book that is like a reference, and it just has 1000 examples, like, "to do random numbers, do this..." and then the shortest, cleanest possible way to do it.  Maybe there'd be a chance that people would stop coding so much and get something done.

  • A Nonny Mouse (unregistered) in reply to Xandax
    Xandax:
    Anonymous:

    i like these in particular

                                } // end for
                            } // end if hash_bytes
                        } // end if val non null
                    } // end if key non null
                } // end while e.hasMoreElements

     so THAT's what }'s do...!

    Actually - I do some similar myself as it often helps my overview of the indentation, rather then having to trace an ending scope up to the starting point.

     

    For a looooong block of code, sure. But for code you can see all on one page? Like for a 3 line for loop? You must be kidding.

  • (cs) in reply to A Nonny Mouse

    "so THAT's what }'s do...!"

    You'll notice that '}' is in fact an overloaded operator; sometimes it ends an 'if' block, sometimes it ends a 'for' block, sometimes a 'while' block... and that's just in this one code snippet!

    It's entirely appropriate to add comments clarifying their usage.

     

  • (cs) in reply to A Nonny Mouse

    Anonymous:
    Xandax:
    Anonymous:

    i like these in particular

                                } // end for
                            } // end if hash_bytes
                        } // end if val non null
                    } // end if key non null
                } // end while e.hasMoreElements

     so THAT's what }'s do...!

    Actually - I do some similar myself as it often helps my overview of the indentation, rather then having to trace an ending scope up to the starting point.

     

    For a looooong block of code, sure. But for code you can see all on one page? Like for a 3 line for loop? You must be kidding.

    If you are used to putting comments after }'s then you probably do it out of habit. I would say either do it or don't do it for the sake of consistency.

  • (cs) in reply to A Nonny Mouse
    Anonymous:
    Xandax:
    Anonymous:

    i like these in particular

                                } // end for
                            } // end if hash_bytes
                        } // end if val non null
                    } // end if key non null
                } // end while e.hasMoreElements

     so THAT's what }'s do...!

    Actually - I do some similar myself as it often helps my overview of the indentation, rather then having to trace an ending scope up to the starting point.

     

    For a looooong block of code, sure. But for code you can see all on one page? Like for a 3 line for loop? You must be kidding.

    Really, those kinds of comments can be quite useful to the maintenance programmer.  Maybe not here, but it's useful sometimes when you'll have logic that looks like this:

              }
            }
          }
          else
          {

    Having a comment lets you know which if that else corresponds to.  Of course, there is usually some way to simplify the logic, but that's a different topic.. 

  • SusieJ (unregistered)

    Tell me this was written by first-time co-op students. 'Cause that's what I was when I "invented" my own random number generator.

  • (cs)
    Michael Casadevall:
    public static byte[] getRandomBits() {
    byte[] random = new byte[32];
    Random.nextBytes(random);
    return random;
    }

     

    There's a mistake here: nextBytes() isn't a static method, so you should probably have something like:

    private static Random random = new Random();
    public static getRandomBytes() {
        byte[] bytes =  new byte[32];
        random.nextBytes(bytes);
        return bytes;
    }

     I didn't know about the SecureRandom class--will remember that one.

  • (cs) in reply to Eli

    Anonymous:

    I don't think the author was going for a GUID. Yes, it's based on some values that are related to that particular system, but there's certainly no guarantee that the number is globally unique. You'd get just as good a GUID from plain old Random(). Face it, this is just a very poor implementation of a psuedo random number generator.

    My favorite part is the bit where it eats the exception for grabbing system data. So... if something goes wrong, it will just silently hash the system clock? Awesome.

    I never said that this horrible code would actually give you a valid GUID, my suggestion was that perhaps he was trying to generate a GUID. For example, Microsoft's implementation for GUIDs is based on a system identifer and the current timestamp, which sounds an awful lot like what this guy was trying to do.

  • mav (unregistered) in reply to SusieJ

    Almost makes me wonder if he copied someone's hashing code and gave it some pseudo-random data and called it "random".

  • (cs) in reply to sir_flexalot

    sir_flexalot:
    This is the trouble with java programming books.  They talk all about sorts, arrays, etc. and so people think that you have to use sorts and arrays at all times.  Someone should really come up with a book that is like a reference, and it just has 1000 examples, like, "to do random numbers, do this..." and then the shortest, cleanest possible way to do it.  Maybe there'd be a chance that people would stop coding so much and get something done.

     

    Make it so.... 

  • (cs)

    I suppose this way is more "randommer" than the other way.

  • sf (unregistered)

    Michael Casadevall:

    <snip attempts at randomness by iterating a fixed number of times of single values anded and shifted fixed lengths...> 

    Thread.yield();

    <snip more same the same...> 

    At least he's conciencous to his fellow threads while burning all those cycles.

  • sf (unregistered) in reply to sf
    Anonymous:

    Michael Casadevall:

    <snip attempts at randomness by iterating a fixed number of times of single values anded and shifted fixed lengths...> 

    Thread.yield();

    <snip more same the same...> 

    At least he's conciencous to his fellow threads while burning all those cycles.

    Make that conscientious.  Typical developer spelling skills ;-O

  • (cs) in reply to sf
    Anonymous:

    Michael Casadevall:

    <snip attempts at randomness by iterating a fixed number of times of single values anded and shifted fixed lengths...> 

    Thread.yield();

    <snip more same the same...> 

    At least he's conciencous to his fellow threads while burning all those cycles.

    On the off chance anyone isn't aware, this is more or less how java's SecureRandom is implemented -- it fires up a bunch of threads, and uses data on how the OS allocates time to them as a source of entropy. 

  • Alessandro (unregistered) in reply to sf

    I realize this is a blog and not "The New Yorker", but talking about spelling, I would suggest the post writer would use some sort of automated spell-checker the next time.  There were enough mistakes to make the post hard to understand.

     

    Having said that, it seems to me that the function in question produces the randommest random that could be randommed.  And, if the author was paid by code lines, he was smarter than we think.

  • (cs) in reply to kipthegreat
    kipthegreat:
    Anonymous:
    Xandax:
    Anonymous:

    i like these in particular

                                } // end for
                            } // end if hash_bytes
                        } // end if val non null
                    } // end if key non null
                } // end while e.hasMoreElements

     so THAT's what }'s do...!

    Several IDEs do this for you automatically..when you open a method, loop etc..., it automatically creates a close brace with the appropriate closing comment.

    Actually - I do some similar myself as it often helps my overview of the indentation, rather then having to trace an ending scope up to the starting point.

     

    For a looooong block of code, sure. But for code you can see all on one page? Like for a 3 line for loop? You must be kidding.

    Really, those kinds of comments can be quite useful to the maintenance programmer.  Maybe not here, but it's useful sometimes when you'll have logic that looks like this:

              }
            }
          }
          else
          {

    Having a comment lets you know which if that else corresponds to.  Of course, there is usually some way to simplify the logic, but that's a different topic.. 

  • (cs) in reply to Xandax
    Xandax:
    Anonymous:

    i like these in particular

                                } // end for
                            } // end if hash_bytes
                        } // end if val non null
                    } // end if key non null
                } // end while e.hasMoreElements

     so THAT's what }'s do...!

    Actually - I do some similar myself as it often helps my overview of the indentation, rather then having to trace an ending scope up to the starting point.

     

    I used to add these comments before the existence of modern* editors and IDEs that easily show the matching brace.

    *Less than 10 years old

  • Gus (unregistered) in reply to sinistral

    or... http://java.sun.com/developer/Books/effectivejava/

  • (cs) in reply to A Nonny Mouse
    Anonymous:

    i like these in particular

                                } // end for
                            } // end if hash_bytes
                        } // end if val non null
                    } // end if key non null
                } // end while e.hasMoreElements

     so THAT's what }'s do...!

    Not to start a flame war or anything..... :>..... but explaining which block the } ends is important if you do that lame-assed start-a-block-on-the-same-line-that-you-declare-it thing.

    You know....

    if(foo) {
    bar();
    }

  • Pool's Closed (unregistered)

    The real wtf here is that I have aids AMIRITE PPL???!

  • Jeff (unregistered)

    Aaugh! Please tell me that none of you laughing at this WTF will ever write cryptography code (excepting those few who pointed out that the built-in Random is bad too.)

    This is the only way to produce a reasonably secure random number in software. Java.security.SecureRandom might be better, but guess how it works? By hashing together a bunch of system values, along with the time, a counter, recent mouse input, etc. And if the author of the snippet had some experience, he'd know to never trust the random functions that come with your library for crypto purposes, because they're usually crap. (The best thing to do would be to use java.security.SecureRandom, *and* all the stuff he's doing here, and hash those together.)

  • Patrick (unregistered) in reply to MichaelWojcik

    The documentation is qutie clear in the Javadocs how Random generates a number.  If  Random isn't appropriate, java also provides a few classes to randomly generate cryptographicaly secure keys.  Either way, that Christmas Tree of code is quite the WTF?  At least break it apart so it's readable.

  • (cs) in reply to Alessandro
    Anonymous:

    I realize this is a blog and not "The New Yorker", but talking about spelling, I would suggest the post writer would use some sort of automated spell-checker the next time.  There were enough mistakes to make the post hard to understand.


    I don't know about anyone else, but I've got a spell-chicker.  It's even intigrated into my web browser.  The WTF is that teh TDWTF super-duper rich-text-with-bells-and-whistles post editer, however, keep sme from usnig it.
  • (cs) in reply to MichaelWojcik
    MichaelWojcik:
    Michael Casadevall:

    The function, getRandomBits() returns a 32-byte array of random bites for security purposes. Since Java provides a Random method, this should be easy...

    If this is in fact "for security purposes", then using Java's Random method would be as equally WTFy (and the five-line implementation is no more "correct" than the long one).

    There is no "correct" way to generate pseudorandom data.  That's a domain-dependent function; the PRNG has to meet the particular requirements of the task.  In this case, of course, we have no information on those requirements other than "for security purposes", but if that's at all accurate we have some reason to believe that Java's Random would be quite wrong as well.

    I rarely use Java, so my docs are well out of date, but I note that there at least used to be a java.security.SecureRandom, which at least claims to be suitable for some security purposes.

    But what this item shows is that security code shouldn't be written by non-experts - and that's so well established it can hardly be counted a WTF.

     

    I bet there was no requirement for the method to give identical numbers if called twice within a millisecond. 

    You'rre right about the SecureRandom part though, but using SecureRandom is  just as simple as using Random. SecureRandom not just claims to be suitable for security purposes, you can choose from a number of standard algorithms (sure, there is no perfect one, but at least the built-in providers are definitely compliant with the relevant standards) and I think there should be native SecureRandom providers that use specialized random generator hardware.

  • jrockway (unregistered) in reply to Xandax

    Actually - I do some similar myself as it often helps my overview of the indentation, rather then having to trace an ending scope up to the starting point.

    % or M-x show-matching-paren

  • (cs) in reply to Jeff
    Anonymous:

    Aaugh! Please tell me that none of you laughing at this WTF will ever write cryptography code (excepting those few who pointed out that the built-in Random is bad too.)

    This is the only way to produce a reasonably secure random number in software. Java.security.SecureRandom might be better, but guess how it works? By hashing together a bunch of system values, along with the time, a counter, recent mouse input, etc. And if the author of the snippet had some experience, he'd know to never trust the random functions that come with your library for crypto purposes, because they're usually crap. (The best thing to do would be to use java.security.SecureRandom, *and* all the stuff he's doing here, and hash those together.)


    No, if you want a reasonably secure random number, you use a hardware random number generator.  Something like an A-D converter connected to a radio tuned to static, or a geiger counter listening to background radiation.  Some computers have internal hardware RNGs that work off the thermal noise in a semiconductor junction.

    Failing that, you use something like Linux's /dev/random, which produces a hash of recent random hardware events, like hard drive access timings, or mouse movement, or keyboard input timings.

    You never use predictable values in your secure random number generator.  System properties are right out, as is absolute time.
  • Random() (unregistered) in reply to biziclop

    Maybe he was using the code itself as an input to another hashing algorithm?

  • (cs)

    Btw, isn't anyone annoyed by the magic numbers in this code? Being a maintainer, reading "(nbytes + 7)/8 " or "for( int i = 512/8;..." drives me crazy.

  • mathew (unregistered) in reply to Rick

    I used to add these comments before the existence of modern* editors and IDEs that easily show the matching brace.

    *Less than 10 years old

    10 years? More like 30. Regular vi had code block navigation in 1976.


    mathew 

  • eq (unregistered) in reply to Carnildo

     
    To reiterate what several posters have said because it's something that is poorly undestood - Random is a "psuedo random number generator". If you draw enough values the moments will converge to that of a uniform distribution, but they are highly predictable. The most basic implementation (linear congruential generator) is x(n) = a x(n-1) + p Mod M where x(n-1) is the last value in the sequence and x(n) is the next. a, p and M are constant parameters which have to be carefully selected. So if you know x(n-1) and the parameters - x(n) is known with 100% certainty! Random should only be used for Monte-Carlo simulation - not for Cryptography!

  • sf (unregistered) in reply to Jeff
    Anonymous:

    Aaugh! Please tell me that none of you laughing at this WTF will ever write cryptography code (excepting those few who pointed out that the built-in Random is bad too.)

    This is the only way to produce a reasonably secure random number in software. Java.security.SecureRandom might be better, but guess how it works? By hashing together a bunch of system values, along with the time, a counter, recent mouse input, etc. And if the author of the snippet had some experience, he'd know to never trust the random functions that come with your library for crypto purposes, because they're usually crap. (The best thing to do would be to use java.security.SecureRandom, *and* all the stuff he's doing here, and hash those together.)

      But some of the key points you are making is exactly what he is NOT doing, namely a counter (seed) and recent mouse input.  His elaborate hashing of the System properties is pointless because they typically never change during the life of the VM's execution.  Even his labor intensive hashing of the one randomish value he is mixing in, the system time, is pointless since he is looping a consant number of times, always shifting a constant amount, and always anding consant value, with no other seed or anything involved.

  • Eli (unregistered) in reply to Alessandro
    Anonymous:

    I realize this is a blog and not "The New Yorker", but talking about spelling, I would suggest the post writer would use some sort of automated spell-checker the next time.  There were enough mistakes to make the post hard to understand.

    If you're going flame someone over his or her spelling, you could at least take the time to check your grammar. Perhaps there's some sort of automated grammar checker you can use?

    That sentence is a comma splice, "spell-checker" should not be hyphenated, and in American English the comma goes inside that quotation marks.

    See what happens when you go down this road?

  • (cs) in reply to Whiskey Tango Foxtrot? Over.
    Whiskey Tango Foxtrot? Over.:
    Anonymous:

    i like these in particular

                                } // end for
                            } // end if hash_bytes
                        } // end if val non null
                    } // end if key non null
                } // end while e.hasMoreElements

     so THAT's what }'s do...!

    Not to start a flame war or anything..... :>..... but explaining which block the } ends is important if you do that lame-assed start-a-block-on-the-same-line-that-you-declare-it thing.

    You know....

    if(foo) {
    bar();
    }

    You must have forgot the WITHOUT INDENTATION part...

  • sf (unregistered) in reply to biziclop
    biziclop:
    MichaelWojcik:
    Michael Casadevall:

    The function, getRandomBits() returns a 32-byte array of random bites for security purposes. Since Java provides a Random method, this should be easy...

    If this is in fact "for security purposes", then using Java's Random method would be as equally WTFy (and the five-line implementation is no more "correct" than the long one).

    There is no "correct" way to generate pseudorandom data.  That's a domain-dependent function; the PRNG has to meet the particular requirements of the task.  In this case, of course, we have no information on those requirements other than "for security purposes", but if that's at all accurate we have some reason to believe that Java's Random would be quite wrong as well.

    I rarely use Java, so my docs are well out of date, but I note that there at least used to be a java.security.SecureRandom, which at least claims to be suitable for some security purposes.

    But what this item shows is that security code shouldn't be written by non-experts - and that's so well established it can hardly be counted a WTF.

     

    I bet there was no requirement for the method to give identical numbers if called twice within a millisecond. 

    You'rre right about the SecureRandom part though, but using SecureRandom is  just as simple as using Random. SecureRandom not just claims to be suitable for security purposes, you can choose from a number of standard algorithms (sure, there is no perfect one, but at least the built-in providers are definitely compliant with the relevant standards) and I think there should be native SecureRandom providers that use specialized random generator hardware.

    SecureRandom is just a wrapper and delegates most of its work to an underlying "service provider" random generator.  So if you don't like what the generators that Sun ships you can write your own and just plug it in.

     You may not want to ask this guy though.

Leave a comment on “Random Ways To Get To Random()”

Log In or post as a guest

Replying to comment #:

« Return to Article