Searching...
Friday, 25 October 2013

How to generate password in java?

10:18

In Java SecureRandom class provides a cryptographically strong random number generator (RNG). Here is one simple example to generate password using SecureRandom class and applying simple rules.

Example

package com.pretech;
import java.security.SecureRandom;
public class SecureRandomExample {
	private static final int PASSWORD_LENGTH = 8;
	private static final int[][] PASSWORD_RULES = new int[][] { { '0', '9' },
			{ 'A', 'Z' }, { 'a', 'z' } };
	public static void main(String[] args) {
		try {
			System.out.println(generatePassword("pretech", PASSWORD_LENGTH,
					PASSWORD_RULES));
			System.out.println(generatePassword("pretech1", PASSWORD_LENGTH,
					PASSWORD_RULES));
			System.out.println(generatePassword("pretech2", PASSWORD_LENGTH,
					PASSWORD_RULES));
			System.out.println(generatePassword("pretech3", PASSWORD_LENGTH,
					PASSWORD_RULES));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static String generatePassword(String seed, int len, int[][] rules)
			throws Exception {
		StringBuffer password = new StringBuffer();
		try {
			SecureRandom rnd = new SecureRandom();
			rnd.setSeed(seed.getBytes());
			int rulesCount = rules.length;
			int numPos = rnd.nextInt(len);
			for (int i = 0; i < len; i++) {
				int rulesIndex = 0;
				if (i != numPos) {
					rulesIndex = rnd.nextInt(rulesCount);
				}
				int base = rules[rulesIndex][0];
				int ch = base + rnd.nextInt(rules[rulesIndex][1] - base);
				password.append((char) ch);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return password.toString();
	}
}

Output



fQ334mua
6P17f3Eg
62142a5j
v05si1va


0 comments: