Monday, December 8, 2014

Make some random Unicode text with this Java class

Our search for randomness brought us to play with Java's "SecureRandom" class. As you would expect, it delivers more randomness than the old "Random". Just saying.

If you need the best randomness currently available, visit RANDOM.ORG. You can get some cool super random bytes, ints, strings, for free. If you need lots, they have a subscription model too.

/*
 * This class uses Java SecureRandom to generate a file of "secure random"
 * Unicode characters. After cleanup for xml 1.0, we save it as a simple properties file.
 *
 * Do whatever you want with this.
 * Really  * 
 */
import java.io.File;
import java.io.FileOutputStream;
import java.security.SecureRandom;
import java.util.Properties;

public class GenerateRandomText {

    /**
     * @param args
     */
    public static void main(String[] args) {

        int codepoint;
        StringBuilder sb = new StringBuilder();
        int line = 0;
        String newline = "\n";

        try {
            // Initialize a secure random number generator
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            // we want 40 000 characters
            for (int x = 0; x < 40000; x++) {

            // get chars up to U 40 000, don't get ASCII, so just do + 255
                codepoint = secureRandom.nextInt(40000) + 255;
            // System.out.println("codepoint> "+codepoint);

                line++;

                // make it pretty by adding a newline
                 if (line > 100) {
                    sb.append(newline);
                    line = 0;
                } else // cleanup
                     if ((codepoint == 0x9)
                        || (codepoint == 0xA)
                        || (codepoint == 0xD)
                        || ((codepoint >= 0x20) && (codepoint <= 0xD7FF))
                        || ((codepoint >= 0xE000) && (codepoint <= 0xFFFD))
                        || ((codepoint >= 0x10000) && (codepoint <= 0x10FFFF))) {
                    sb.append(Character.toChars(codepoint));
                }

            }


            File outputfile = new File(new File(".").getCanonicalPath() + "randomText.xml");
            Properties props = new Properties();
            props.put("page", sb.toString());

            FileOutputStream outf = new FileOutputStream(outputfile);
            props.storeToXML(outf, "-- random generated Unicode --");

            outf.flush();
            outf.close();
        } catch (Exception e) {
        }

    }

}

No comments:

Post a Comment