import java.math.*; import java.security.*; class GenKey { // Generate some large primes in the 128 bit area. // // Possibly useful for lotteries where winning numbers // are "probably" large prime numbers. // // The purpose of this code is generate keys from some sort // of input - in this case the command line. The intention // is not to generate a random prime number but a reproducible // number. // // Copyright 1998 by Michael Lecuyer. You may use this in any way // you wish, but this version is mine. Change it enough and you'll get // to place your copyright notice here instead! // public static void main(String args[]) { int i; BigInteger biKey; // resulting key. BigInteger two = new BigInteger("2"); BigInteger one = new BigInteger("1"); // nth probable prime to pick. Choose your own number. int pick = 5; if (args.length == 0) { System.err.println("Usage: Some phrase like 'hello fishy'"); System.exit(1); } // Accumulate all args into a string and convert it to MD5. String seed = ""; for (i = 0; i < args.length; i++) seed += args[i]; MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.err.println("Can't find an MD5 message digest algorithm"); } biKey = new BigInteger(md5.digest(seed.getBytes())); // make sure it starts out odd - there are very few even primes. if (biKey.and(one).compareTo(one) != 0) biKey = biKey.add(one); // Purely for entertainment purposes! System.out.println("Key starts with: " + dumpBytes(biKey.toByteArray())); // Search for n'th probable prime out of a thousand. for (i = 0; i < 1000; i++) { // The number 1024 was chosen at pseudorandom. Larger numbers // take longer because the prime-picker is allegedly more picky. if (biKey.isProbablePrime(1024)) if (--pick == 0) { System.out.println("Key: " + dumpBytes(biKey.toByteArray())); System.exit(0); } biKey = biKey.add(two); } System.out.println("No Key Generated."); } // Display some bytes in HEX. // static String dumpBytes(byte b[]) { StringBuffer r = new StringBuffer(); final String hex = "0123456789ABCDEF"; for (int i = 0; i < b.length; i++) { int c = ((b[i]) >>> 4) & 0xf; r.append(hex.charAt(c)); c = ((int)b[i] & 0xf); r.append(hex.charAt(c)); // r.append(' '); // uncomment if you like spaces in the dump. } r.setLength(r.length() - 1); return r.toString(); } }