Java MessageDigest create random String
import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; public class Main { private static SecureRandom prng; static {//from w w w.ja v a 2 s. c o m try { // Initialize SecureRandom prng = SecureRandom.getInstance("SHA1PRNG"); } catch (NoSuchAlgorithmException e) { System.out.println("ERROR while intantiating Secure Random : " + prng); } } public static void main(String[] args) { System.out.println(getToken()); System.out.println(getToken()); } public static String getToken() { try { String token; // generate a random number String randomNum = Integer.toString(prng.nextInt()); // get its digest MessageDigest sha = MessageDigest.getInstance("SHA-1"); byte[] result = sha.digest(randomNum.getBytes()); token = hexEncode(result); return token; } catch (NoSuchAlgorithmException ex) { return null; } } private static String hexEncode(byte[] aInput) { StringBuilder result = new StringBuilder(); char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; for (byte b : aInput) { result.append(digits[(b & 0xf0) >> 4]); result.append(digits[b & 0x0f]); } return result.toString(); } }