• (cs) in reply to gwenhwyfaer
    gwenhwyfaer:

    DWalker59:
    The best way to get randomness, I have heard, is in hardware... have the software "listen" to the noise generated by a resistor and use that.

    Or a noise diode. I'm honestly amazed that there aren't noise generator / sampler circuits routinely included in machines. I suppose the issue is whether analogue noise is sufficiently random...? (I'm not prepared to accept that cost is significant; we're talking about a latch, a comparator and a diode.)

    They are. Not in home machines because you don't need that much security there (actually you need it but nobody seems to bother) but I've seen servers being shipped with these thermal noise sampling gadgets. 

  • (cs) in reply to Rich

    And in fact, that is typically the case for pseudo-random numbers. Though the number returned may not actually be the seed itself, it will depend on the seed.

    But that's a key difference.  If I have a 32-bit internal seed, and I return the lower 16-bits as the new value, then having 23456 follow 12345 once, does not mean that it will follow 12345 next time.

    A 16 bit seed limits you to 65536 values however you slice it.

    No. It limits you to 65536 different sequences of numbers, and since we are calling it 5 times to build one number, it's the sequence that is important.

    To demostrate, let's say I has a (very bad) PRNG which just returns this sequence: 1,2,3,4,5,1,2,3,4,5 over & over.  If I were to build IDs using the formula (rnd * 10 + rnd), then I'd get only 5 ids : 12, 34, 51, 23 & 45.  This is your point.  However, my point is that if a different seed were to give the same numbers in a different sequence, (say, 2,4,1,3,5), we'd get another 5 ids: 24, 13, 52, 41, 35. If 5 different seed give us 5 different sequences, then we have 25 different ids possibly generated.

     

  • Anthony Martin (unregistered) in reply to mustache

    What version of Java has Random.nextBytes(byte[]) (static method)?  Shouldn't it be:


    new Random(System.currentTimeMillis()).nextBytes(random);

  • (cs) in reply to Anon
    Anonymous:
    Rootbeer:

    "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.

     

    If by appropriate you meant "pointless" then I totally agree.

    This post was brought to you by the letters I, D and E.

     

    One might argue (and might even be right) that you should never write a block that's longer than one page but if you do, just put those comments there. It won't make your code any worse but maintainers will surely love you. Being one of those poor souls who try to maintain the unmaintainable, all I can say is that while I do have an IDE , I appreciate every little attempt of the coders to help my job. Even if it doesn't help too much.

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

    In 25 years, I've never seen anyone do this for a fractional number of bits, but then, this is TDWTF!

    Cryptography, compression, networking, and audio/visual encoding almost always works on bits instead of bytes.

    But he's not talking about fractional byte, but fractional bits, (which, being the atoms of computer logic, cannot be subdivided)

  • Anthony Martin (unregistered) in reply to Anthony Martin

    Here is the Random class encapsulated in an InputStream:


    http://msuapi.cvs.sourceforge.net/msuapi/martin-studio-useless-api/src/martinStudio/useless/io/RandomInputStream.java?revision=1.7&view=markup

  • (cs) in reply to Eli
    Anonymous:
    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?

    "American English", both the phrase and what it refers to, is a WTF itself. The commas in that case and this one go outside the quotes. Commas go within quotes to denote more speech to follow, which is not the case here.
     

  • fivetrees (unregistered) in reply to PseudoNoise
    Anonymous:
    fivetrees:

    Absolutely right. The opening-brace-on-the-same-line made sense in the days of printed listing - not any more. (And for consistency, one should put the closing brace at the end of the final line of code, right?)

    For Xmas, give yourselves braces that line up, and no closing "this is what this brace does" comments - if it really needs them, the block is too long, so break it down further. And ho ho ho.

    Steve

    captcha: pizza. yum.

     We still do code reviews here with printed listings.  We have some online code review type applications, but they've never taken hold.

     So when printing out functions, even if they're small, they'll often go across page breaks.  It's very handy to have the end-brace comment.  Also, when modifying code, sometimes it can be easy to get lost (as with the 5 closing braces in the example) for somebody to maintain.

    Hmmm. Back in the days of ASM51, there was a pagebreak directive for just this purpose ("if you really want to print the listing, let's help make it readable"). Hell, there probably still is. But not in C... It's a page layout issue, which is quite different from code quality issues. Separate the issues and survive.

    Anonymous:

    Count me on the "comments are never bad unless they're wrong or misleading" side of this jihad.

    In general, I'd agree. But I've seen comments go stale too often. Including such "here endeth the loop" comments. Comments tend to become wrong/misleading over time. Nowadays, I prefer (to read and write) code that's so transparent that we don't need no steenking comments.

    Steve

    captcha: captcha. blimey: blimey.

  • (cs) in reply to Anthony Martin

    As the guy who submitted this WTF, I'll make a quick defense of my "fix". First, what I posted here was dashed off on the fly in the submission form, without a compiler handy and without bothering to look up whether nextBytes() is static. The real version uses SecureRandom and works properly. Furthermore, the bytes returned from this method aren't used directly, but are used to seed a different PRNG algorithm.

     As the security geeks have pointed out, even SecureRandom isn't all that entropic, but it's the best thing at my disposal, and it's a hell of a lot better than what came before. If there's a better option that makes the paranoid happy and will run (1) quickly, (2) without requiring user interaction (e.g. by moving the mouse to generate entropy), and (3) without touching the internet (e.g. no calls to HotBits), then let me know.
     

  • fivetrees (unregistered) in reply to m0ffx
    m0ffx:
    Anonymous:
    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?

    "American English", both the phrase and what it refers to, is a WTF itself. The commas in that case and this one go outside the quotes. Commas go within quotes to denote more speech to follow, which is not the case here.


     

    Yep, quite right. The comma in this case belongs outside the quote. Putting it inside the quote results in a syntax error and a fatal exception in my brain. Have mercy, please.

    Meanwhile, back at the original post: "getRandomBits() returns a 32-byte array of random bites" and "in fact a proper implementation can be writting in five lines"... Bites? Writting? WTF?

    Steve

  • Ryan (unregistered) in reply to Michael Casadevall

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

    Yes, CryptGenRandom and similar parts of the Win32 CryptoAPI have these functions. They are based on a Yarrow-like secure RNG.

  • (cs) in reply to gwenhwyfaer
    gwenhwyfaer:

    DWalker59:
    The best way to get randomness, I have heard, is in hardware... have the software "listen" to the noise generated by a resistor and use that.

    Or a noise diode. I'm honestly amazed that there aren't noise generator / sampler circuits routinely included in machines. I suppose the issue is whether analogue noise is sufficiently random...? (I'm not prepared to accept that cost is significant; we're talking about a latch, a comparator and a diode.)


    They're starting to show up.  Servers routinely have them, as do the AMD mini-ITX mainboards.
  • (cs)

    The basic idea of being secure is do not trust to anybody. The guy who wrote the snippet obviously didn't trust to securerandom so he wrote it his way and he proved good skills by doing so. I would never trust to any set of "random numbers" coming out of a blackbox which is 1's and 0's and tick - tack - tick - tack and honestly don't know how to implement features like mouse capturing if the code is supposed to run on a handset. I hope it's hard to predict when the System.gc() comes ;-)

  • (cs) in reply to Michael Casadevall
    Michael Casadevall:
    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 ;-).
    <font size="+1">T</font>he source for the Java classes has always been available in the JDK in the file source.zip.
  • rotu (unregistered) in reply to A Nonny Mouse

    re: 

    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...!

     

     -------------------------

    so what's wrong with that? when a code gets long enough to actually scroll the screen, this is one way to keep track of which ending caret goes with which beginning caret. I used to do this when I was coding using a vanilla text editor.

  • tester (unregistered) in reply to A Nonny Mouse

    Xandax:

    [image] 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.

     

    -----------------------

    you must me shortsighted not to anticipate a block of code getting longer in the future. there are some times when a block of code becomes really long before refactoring. 

  • JavaMaster (unregistered)

    Actually, this would be even better because calling getRandomBytes twice in one millisecond will result in different values:

     

    <font color="#7f0055" size="2">

    import<font size="2"> java.util.Random;

     

    </font>

    </font>
    <font size="2"> java.util.Random;

     

    </font><font color="#7f0055" size="2">

    public<font size="2"> </font><font color="#7f0055" size="2">class</font><font size="2"> ByteUtils {

     

    <font color="#7f0055" size="2">private</font><font size="2"> </font><font color="#7f0055" size="2">static</font><font size="2"> </font><font color="#7f0055" size="2">long</font><font size="2"> </font><font color="#0000c0" size="2">seed</font><font size="2"> = System.currentTimeMillis() ;

     

    <font color="#7f0055" size="2">public</font><font size="2"> </font><font color="#7f0055" size="2">static</font><font size="2"> </font><font color="#7f0055" size="2">byte</font><font size="2">[] getRandomBytes ( ) {

    <font color="#7f0055" size="2">byte</font><font size="2">[] retVal = </font><font color="#7f0055" size="2">new</font><font size="2"> </font><font color="#7f0055" size="2">byte</font><font size="2">[32] ;

    Random random = <font color="#7f0055" size="2">new</font><font size="2"> Random(</font><font color="#0000c0" size="2">seed</font><font size="2">) ;

    random.nextBytes(retVal) ;

    <font color="#0000c0" size="2">seed</font><font size="2"> = random.nextLong() ;

    <font color="#7f0055" size="2">return</font><font size="2"> retVal ;

    }

    }

    </font>

    </font>

    </font>

    </font>

    </font>

    </font>

    </font>

    </font>
    <font size="2"> </font><font color="#7f0055" size="2">class</font><font size="2"> ByteUtils {

     

    <font color="#7f0055" size="2">private</font><font size="2"> </font><font color="#7f0055" size="2">static</font><font size="2"> </font><font color="#7f0055" size="2">long</font><font size="2"> </font><font color="#0000c0" size="2">seed</font><font size="2"> = System.currentTimeMillis() ;

     

    <font color="#7f0055" size="2">public</font><font size="2"> </font><font color="#7f0055" size="2">static</font><font size="2"> </font><font color="#7f0055" size="2">byte</font><font size="2">[] getRandomBytes ( ) {

    <font color="#7f0055" size="2">byte</font><font size="2">[] retVal = </font><font color="#7f0055" size="2">new</font><font size="2"> </font><font color="#7f0055" size="2">byte</font><font size="2">[32] ;

    Random random = <font color="#7f0055" size="2">new</font><font size="2"> Random(</font><font color="#0000c0" size="2">seed</font><font size="2">) ;

    random.nextBytes(retVal) ;

    <font color="#0000c0" size="2">seed</font><font size="2"> = random.nextLong() ;

    <font color="#7f0055" size="2">return</font><font size="2"> retVal ;

    }

    }

    </font>

    </font>

    </font>

    </font>

    </font>

    </font>

    </font><font color="#7f0055" size="2">private</font><font size="2"> </font><font color="#7f0055" size="2">static</font><font size="2"> </font><font color="#7f0055" size="2">long</font><font size="2"> </font><font color="#0000c0" size="2">seed</font><font size="2"> = System.currentTimeMillis() ;

     

    <font color="#7f0055" size="2">public</font><font size="2"> </font><font color="#7f0055" size="2">static</font><font size="2"> </font><font color="#7f0055" size="2">byte</font><font size="2">[] getRandomBytes ( ) {

    <font color="#7f0055" size="2">byte</font><font size="2">[] retVal = </font><font color="#7f0055" size="2">new</font><font size="2"> </font><font color="#7f0055" size="2">byte</font><font size="2">[32] ;

    Random random = <font color="#7f0055" size="2">new</font><font size="2"> Random(</font><font color="#0000c0" size="2">seed</font><font size="2">) ;

    random.nextBytes(retVal) ;

    <font color="#0000c0" size="2">seed</font><font size="2"> = random.nextLong() ;

    <font color="#7f0055" size="2">return</font><font size="2"> retVal ;

    }

    }

    </font>

    </font>

    </font>

    </font>

    </font>

    </font><font color="#7f0055" size="2">public</font><font size="2"> </font><font color="#7f0055" size="2">static</font><font size="2"> </font><font color="#7f0055" size="2">byte</font><font size="2">[] getRandomBytes ( ) {

    <font color="#7f0055" size="2">byte</font><font size="2">[] retVal = </font><font color="#7f0055" size="2">new</font><font size="2"> </font><font color="#7f0055" size="2">byte</font><font size="2">[32] ;

    Random random = <font color="#7f0055" size="2">new</font><font size="2"> Random(</font><font color="#0000c0" size="2">seed</font><font size="2">) ;

    random.nextBytes(retVal) ;

    <font color="#0000c0" size="2">seed</font><font size="2"> = random.nextLong() ;

    <font color="#7f0055" size="2">return</font><font size="2"> retVal ;

    }

    }

    </font>

    </font>

    </font>

    </font>

    </font><font color="#7f0055" size="2">byte</font><font size="2">[] retVal = </font><font color="#7f0055" size="2">new</font><font size="2"> </font><font color="#7f0055" size="2">byte</font><font size="2">[32] ;

    Random random = <font color="#7f0055" size="2">new</font><font size="2"> Random(</font><font color="#0000c0" size="2">seed</font><font size="2">) ;

    random.nextBytes(retVal) ;

    <font color="#0000c0" size="2">seed</font><font size="2"> = random.nextLong() ;

    <font color="#7f0055" size="2">return</font><font size="2"> retVal ;

    }

    }

    </font>

    </font>

    </font>

    </font><font color="#7f0055" size="2">new</font><font size="2"> Random(</font><font color="#0000c0" size="2">seed</font><font size="2">) ;

    random.nextBytes(retVal) ;

    <font color="#0000c0" size="2">seed</font><font size="2"> = random.nextLong() ;

    <font color="#7f0055" size="2">return</font><font size="2"> retVal ;

    }

    }

    </font>

    </font>

    </font><font color="#0000c0" size="2">seed</font><font size="2"> = random.nextLong() ;

    <font color="#7f0055" size="2">return</font><font size="2"> retVal ;

    }

    }

    </font>

    </font><font color="#7f0055" size="2">return</font><font size="2"> retVal ;

    }

    }

    </font>
  • JavaMaster (unregistered) in reply to JavaMaster

    I only pasted a class with one method.  There's something seriously wrong with this forum.

  • WTF Police (unregistered)

    I think the author was trying to generate true-random numbers using real entropy, which pseudo-random algorithms can't do.  This is a non-trivial task, and the snippet is a good attempt, though not the best.  There is a whole industry around deriving ways to use true entropy as a source of randomness in software, from casino applications to simulation programs.

    I think the real WTF here is the person who submitted the entry.  Just because you don't understand it doesn't make it ridiculous.

  • bcdm (unregistered) in reply to fivetrees

    On top of that, this sentence is not a comma splice. The commas are all in acceptable positions.

    As to "spell-checker", this is an acceptable, if not common, usage:

     
    http://dictionary.reference.com/search?q=%22spell-checker%22

     
    Escalating a flame war is only recommended if you have actual fire handy, and not just smoke.

     

  • (cs) in reply to WTF Police
    Anonymous:
    I think the real WTF here is the person who submitted the entry.  Just because you don't understand it doesn't make it ridiculous.


    Yeah, right, wtf is it doing here ? Isn't it kind of security issue too ? This code should never get out in the first place.
  • SpectateSwamp (unregistered) in reply to AstorLights

    I do Random Video, Random Start points and the same for music

    Randomly play the family album of 5000+ pics.

    Good going even if it doesn't work.

    A few CPU cycles, who cares

  • (cs) in reply to JamesCurran
    JamesCurran:
    tegla:

    the WTF here is all the commenters who don't realise this code is OK.

    This creates a random seed from all the available enthropy sources present.

    But, what you don't seem to be realizing is that most of these "entrophy sources" aren't presenting any entrophy.  Most of what he starts with is the bytes of the ASCII representations of "key + val" for the system properties --- where "val" changes little, and "key" doesn't change at all.  He then tossing in the time, but he's using currentTimeMillis, which is the time, in milliseconds, from 1-Jan-1970, which means, an hour from now, most of the bits will still be the same.


    Excellent!

    "At the end of the competition, the winner will be entrophied on the main stage."
  • jokeyxero (unregistered) in reply to A Nonny Mouse

    It becomes a reflex after a while and you just type it, especially if you immediately add a closing brace when you start your open.

     

    In VB I automatically type 'i after I type Next because I've done it so much.  ( For i = 0 to ... Next 'i )

  • (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.

    Actually, why not refacter each block into an easy to understand function?

     

  • Anonymous (unregistered) in reply to Michael Casadevall

    Michael Casadevall:
    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 ;-).

    You don't need to.  The RNG used by Java has been specified in the language specification since Java 1.0.  You can view the algorithm used directly from the java.util.Random javadoc.  (The code is included in the individual method descriptions - scroll down.)

    Unfortunately, because the implementation is spelled out, it also can't be changed, and as other people have mentioned, the default Java implementation of random isn't, exactly, random.

  • (cs)

    Some kids in my computer graphics class were presenting their project, which was a randomly generated landscape scene, and they were talking about how the C standard library's pseudorandom number generator "wasn't random enough" so they implemented their own.


    I just rolled my eyes. I'm pretty sure they just did it because one of them learned how to write pseudorandom number generators and wanted to show off.

    As long as you seed it with the time (or similar) they should be ok, right? It's not like they cryptographically secure random number sequences.

  • gjm (unregistered) in reply to A Nonny Mouse

    Thats the F** problem with C/x. Try Progress. The best 4GL ever written if we talk enterprice. And every time I suggest Progress, all you C+ fuckers object.

    But all of you object because your focus is on C. Progress makes live easy.

    By the way, I think I am in love with the Bean Bag girl. 

     

     

     

  • DLX (unregistered) 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...!

    That is a very, very good practice. In case of such deep functions,  it makes understanding and debugging the code a lot easier. I've spent hours trying to figure out spaghetti code - which would have been way easier if every } would have had a comment denoting the end of which it shows.

     

    Of course, what do I know - even the captcha text for this posting is "stfu"... 

  • Calyth (unregistered) in reply to cheesy

    "As long as you seed it with the time (or similar) they should be ok, right? It's not like they cryptographically secure random number sequences."

    The WTF said that this RNG is for security purposes, so any of the linear congruential generators are not good enough, assuming that security purposes is crypto related.
    Seeding with time also has other problems where if the machines are time synced even with something like NTP, an attacker can potentially try and seed different PNGs if he wants to do it the hard way, or in teh case of linear congruential generators, observe a couple of outputs and try to derive parameters, with a pretty good success rate. Frankly I should read up on it before my take home final on Cryptography tomorrow.
    Java's Random on a cursory glance, does not look like a cryptographically secure. It should be fine for simulation, games, etc.

    And the post about the rand funtion that gave 16-bit numbers for non-secure purposes, couldn't you just generate one, shift it over 16 bits, and add that with a new one, possibly do some more manipulation afterwards? It won't be secure, since most manipulation that you would do to it is linear, but instead of having a cycle of max 5*0xFFFF, you can potentially get 32-bit badly generated pseudo-random numbers? shift ops are not that expensive.

  • dwg (unregistered) in reply to Rootbeer
    Rootbeer:

    "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.

    hmm .. I hope you're kidding. '}' is not an overloaded operator (in fact not even an operator at all) but simply a symbol that denotes the end af a block, ANY block.

    I can write
    {
        int foo = 5;
        System.out.println(foo);
    }
    at any point within a method; it doesn't need to be preceeded by "if", "for", "while" or anything for that matter. A block is simply a statement which (a) contains 0 or more statements and (b) limits the scope of those statements.


    And btw, if anyone feels the need to comment the end of block maybe they should think about refactoring their method.
  • Rob Baillie (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.

     

    If you need to next a for inside an if inside an if inside a while then I reckon you've got at least 3 extract function refactorings to do there.

    Or to put it another way... if you've got a closing brace that's too far away to see its matching brace clearly without comments, then you're writing far too large a monolithic block of code.

    Most of the time.
     

  • (cs) in reply to Rob Baillie
    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.

     

    If you need to next a for inside an if inside an if inside a while then I reckon you've got at least 3 extract function refactorings to do there.

    Or to put it another way... if you've got a closing brace that's too far away to see its matching brace clearly without comments, then you're writing far too large a monolithic block of code.

    Most of the time.
     

    You're right but as I mentioned above, if you happen to write code like this then at least put a comment on the closing braces, making it much easier for your successor to refactor it properly.

  • Remco Gerlich (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.

     

    If you need comments like that, that's a good sign that your block is getting too long and indented too deeply. 

  • (cs) in reply to dj_axl
    dj_axl:
    Random can take a seed value, if one wanted to throw the system time or some other (long) value in there...
    public static getRandomBytes() {
    Random random = new Random(new Date().getTime());

     Guess what new Random() does...
     

  • Brendan (unregistered) in reply to dwg

    Anonymous:

    And btw, if anyone feels the need to comment the end of block maybe they should think about refactoring their method.

    Not always the case... I've seen people comment end braces when the start of the block was two line above.

    I think commenting a brace is rather useful when reading other peoples code.   

  • (cs) in reply to AstorLights

    AstorLights:
    The basic idea of being secure is do not trust to anybody. The guy who wrote the snippet obviously didn't trust to securerandom so he wrote it his way and he proved good skills by doing so. I would never trust to any set of "random numbers" coming out of a blackbox

    No, he proved that he's a total idiot and unskilled programmer by doing so. Blindly trusting a blackbox implementation isn't wise, but rolling your own ad-hoc solution without any theoretical foundation is far, far worse. What you should do is take a standard implementation like SecureRandom and have it inspected closely by someone who actually knows the math behind cryptography. Rolling your own is, as proven here, likely to yield a something much worse than even the weakest standard solution. 

    Anonymous:
    I think the author was trying to generate true-random numbers using real entropy, which pseudo-random algorithms can't do.  This is a non-trivial task, and the snippet is a good attempt, though not the best.

    Um no, it's in fact an absolutely awful attempt. He is using NO "real entropy" whatsoever. A hint "real entropy" is not something you get by writing long, complicated code.  

  • Jeff (unregistered) in reply to sir_flexalot

    I've used this numerous times:

    http://www.exampledepot.com/

  • (cs) in reply to Brendan
    Anonymous:

    Not always the case... I've seen people comment end braces when the start of the block was two line above.

    If by that you mean comments that do nothing but indicate which block is being closed, then that's what I would call "worse than useless" comments, because it adds no information that isn't immediately visible in properly indented code, and instead just clogs up the view of said code.

    Cleanly formated code that is properly divided into units (methods, classes) of appropriate size and uses meaningful identifiers needs very few comments to help understanding. Commends that say things which are already obvious from looking at the code hinder understanding. I'm talking about stuff like:

    /**
     * Returns the xyzzy.
     * 
     * @return the xyzzy
     */
    public int getXyzzy()
    {
        int result; // initialize variable
        result = Integer.parseInt(this.xyzzyString); // convert from String
        return result; // do the return
    }
    

    I can see from the method name that it gives me a bloody xyzzy and how it's implemented! Ironically, this kind of commend usually skips over the stuff that would actually need explanation, namely what the hell a "xyzzy" is.

     

     

  • Anonymous (unregistered) in reply to limelight

    It seems to me that instead of doing that properly he managed to create a random number system that is highly predictable if combined with a tiny information leak from elsewhere.. That piece of code could be extremely DANGEROUS imo.

  • noname (unregistered) in reply to AstorLights

    AstorLights:
    Anonymous:
    I think the real WTF here is the person who submitted the entry.  Just because you don't understand it doesn't make it ridiculous.


    Yeah, right, wtf is it doing here ? Isn't it kind of security issue too ? This code should never get out in the first place.

     Wow, this comment is the real wtf. Any kind of real security does not rely on being unknown. While such security may work in the short term, in the long term it won't Your security measures will get out (or you may not have needed them because noone cares). In fact, if you really care about security, let the whole world know what you are doing and invite them to break in. Give out a nice gift certificate for anyon who succeed and tells you how, then fix your security. This concept has been know for more than 150 years. Sure, computers aren't that old...but lockmakers of olden times knew this concept as well. The only hidden information your lock should have is the key. That's where most security breaks anyway. Keys (passwords) are chosen by people. People think their [birthday|pets name|zipcode|etc] is a good password.

     

    As to the } comment discussion. Mostly I'm pro comment because people tend to undercomment rather than over comment. So I say if it floats your boat, do it. However if you are doing it because your code doesn't fit on your screen, then I hope you are programming on your cell phone. Any procedure that scrolls off the screen is too long by far. there is never a good reason for it. never. even though you're not supposed to ever say never. If you happen to find a counterexample which you can mathematically, socially, aesthetically and any otherly prove to be correct, even then you should'nt do it.
     

  • stm (unregistered) in reply to cheesy
    cheesy:
    Some kids in my computer graphics class were presenting their project, which was a randomly generated landscape scene, and they were talking about how the C standard library's pseudorandom number generator "wasn't random enough" so they implemented their own.

    I just rolled my eyes. I'm pretty sure they just did it because one of them learned how to write pseudorandom number generators and wanted to show off.

    As long as you seed it with the time (or similar) they should be ok, right? It's not like they cryptographically secure random number sequences.


    Random points generated with linear congruential prng all fall on parallel planes, so it is quite possible that standard prng was not good enough. Google "spectral test".
  • (cs) in reply to fivetrees
    Anonymous:

    Hmmm. Back in the days of ASM51, there was a pagebreak directive for just this purpose ("if you really want to print the listing, let's help make it readable"). Hell, there probably still is. But not in C... It's a page layout issue, which is quite different from code quality issues. Separate the issues and survive.

    Well, you could always stick a form-feed character in (ASCII 0x0C, IIRC).  Assuming the printout respects such things, of course. 

  • Brendan (unregistered) in reply to iwpg
    iwpg:
    Anonymous:

    Hmmm. Back in the days of ASM51, there was a pagebreak directive for just this purpose ("if you really want to print the listing, let's help make it readable"). Hell, there probably still is. But not in C... It's a page layout issue, which is quite different from code quality issues. Separate the issues and survive.

    Well, you could always stick a form-feed character in (ASCII 0x0C, IIRC).  Assuming the printout respects such things, of course. 

     That's interesting, I though the char for 0x0c was a<font size="-1"> carriage return and 0x0A was a line-feed</font>

    <font size="-1">CAPTCHA = wtf - makes sense</font>
     

  • Brendan (unregistered) in reply to brazzy
    brazzy:

    Cleanly formated code that is properly divided into units (methods, classes) of appropriate size and uses meaningful identifiers needs very few comments to help understanding. Commends that say things which are already obvious from looking at the code hinder understanding. I'm talking about stuff like:

    /**
    * Returns the xyzzy.
    *
    * @return the xyzzy
    */
    public int getXyzzy()
    {
    int result; // initialize variable
    result = Integer.parseInt(this.xyzzyString); // convert from String
    return result; // do the return
    }

    I can see from the method name that it gives me a bloody xyzzy and how it's implemented! Ironically, this kind of commend usually skips over the stuff that would actually need explanation, namely what the hell a "xyzzy" is.

     

    the code example you gave may need heavy commenting because, it's not good code (i.e that whole function can be done in one line, return Integer.parseInt(this.xyzzyString); ;)). But I do understand what you mean. there's a fine line between to much commenting and not enough.


  • (cs) in reply to Brendan
    Anonymous:

     That's interesting, I though the char for 0x0c was a<font size="2"> carriage return and 0x0A was a line-feed</font>

    Well, now you know you were wrong :)

    (You know you've been trawling through too many Wintel hex dumps when you have got used to the 0D 0A sequence.)
  • (cs) in reply to Brendan
    Anonymous:
    brazzy:

    Cleanly formated code that is properly divided into units (methods, classes) of appropriate size and uses meaningful identifiers needs very few comments to help understanding. Commends that say things which are already obvious from looking at the code hinder understanding. I'm talking about stuff like:

    /**
    * Returns the xyzzy.
    *
    * @return the xyzzy
    */
    public int getXyzzy()
    {
    int result; // initialize variable
    result = Integer.parseInt(this.xyzzyString); // convert from String
    return result; // do the return
    }

    I can see from the method name that it gives me a bloody xyzzy and how it's implemented! Ironically, this kind of commend usually skips over the stuff that would actually need explanation, namely what the hell a "xyzzy" is.

     

    the code example you gave may need heavy commenting because, it's not good code (i.e that whole function can be done in one line, return Integer.parseInt(this.xyzzyString); ;)). But I do understand what you mean. there's a fine line between to much commenting and not enough.


    Every single comment there is either completely pointless, or actually outright wrong. And the comment that is wrong would have been completely pointless. As brazzy was saying, the only comment required is the one that is actually missing - namely what the hell the  point of a xyzzy is.

    Commenting is not there to be a lesson in programming. I only want to see a comment if it is (a) something the code itself doesn't say (like what the xyzzy is for), (b) clarification of something tricky, or (c) an executive summary of what something does. Oh, and stuff being fed to JavaDoc or the like, but that counts as (a) and (c) combined.

    (Oh dear God, this forum editor is still badly broken and wanting to put no-break spaces in all the time if I don't sit on its head and beat it till it's blue.)
  • Wecke (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.

     

    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.

     

    Say, language purist, shouldn't that have been randomnest random that could be randomned? ;-) 

  • (cs) in reply to noname

    AstorLights:

    Yeah, right, wtf is it doing here ? Isn't it kind of security issue too ? This code should never get out in the first place.

    Anonymous:

     Wow, this comment is the real wtf. Any kind of real security does not rely on being unknown. While such security may work in the short term, in the long term it won't Your security measures will get out (or you may not have needed them because noone cares). In fact, if you really care about security, let the whole world know what you are doing and invite them to break in. Give out a nice gift certificate for anyon who succeed and tells you how, then fix your security. This concept has been know for more than 150 years. Sure, computers aren't that old...but lockmakers of olden times knew this concept as well. The only hidden information your lock should have is the key. That's where most security breaks anyway. Keys (passwords) are chosen by people. People think their [birthday|pets name|zipcode|etc] is a good password.



    Heh sure should never rely on being "unknown" to implement security, they say using the name of your secret mistress as your password is good only to find out that everybody around knows about your relationship. I've been talking about possibility of revealing existing security holes to public. Half of the comments here says the code is OK, the other half says it's BAD, I'm not a crypto coding expert so I can't really say whether the SOD-random-generator is or is not a real security hole, but something in it definitely smells. 
  • (cs) in reply to Brendan

    That's interesting, I though the char for 0x0c was a carriage return...

    No Quack. Ctrl-M / 0x0D / Chr(13) is CR. FF is indeed Ctrl-L / 0x0C / Chr(12).
     

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

Log In or post as a guest

Replying to comment #:

« Return to Article