Friday, September 14, 2007

Generating unique strings with JAVA

If you need randomly generated Strings in your java code you can use the below functions.


01  public String generateRandomString(String s) {
02   try {
03    SecureRandom prng = SecureRandom.getInstance("SHA1PRNG");
04    String randomNum = new Integer(prng.nextInt()).toString();
05    randomNum += s;
06    MessageDigest sha = MessageDigest.getInstance("SHA-1");
07    byte[] result = sha.digest(randomNum.getBytes());
08    return hexEncode(result);
09   catch (NoSuchAlgorithmException e) {
10    return  System.currentTimeMillis()+"_"+username;
11   }
12  }


The classical hexEncode method:

01 protected String hexEncode(byte[] aInput) {
02   StringBuffer result = new StringBuffer();
03   char[] digits = '0''1''2''3''4''5''6''7''8''9',
04     'a''b''c''d''e''f' };
05   for (int idx = 0; idx < aInput.length; ++idx) {
06    byte b = aInput[idx];
07    result.append(digits[(b & 0xf0>> 4]);
08    result.append(digits[b & 0x0f]);
09   }
10   return result.toString();
11  }


Suppose that you need to generate unique random session ids for your logged in users. You can use the above function as follows :

String sessionId = generateRandomString(username);


10 consecutive calls to generateRandomString("ilkinulas") generates the following strings:

38aca43c835888bc38fbb2d431f537489d637427
8c9fec7eb1309cd60a9548a11b16a30c2cf277a4
d495e83405704d38bfdf1bc3e2a38b31a5b52243
e3f15b900a3b80936596dc4471c0e42889dbf00c
83a4c869593af633a97b3b68433fac19bac7937d
f7573e8fdb4ecf6f58062570b66943b08d87fab8
c19bfdf75abbafbb5d9ca0ce37b90e97f08fccfa
41f0d9cd01ff814f8879bbff4b06642fc01a4624
aae1a792389239ca8db35a1ff9b16856c9921845
c2c9041ab5039b38c79a125c57a10cc6a3eabad9

0 comments: