package com.iamberry.app.international.util;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.UUID;

/**
 * @website www.ratfw.com
 * @author 献
 * @tel 18271840547
 * @date 2016年8月30日
 * @explain 生成安全随机的token工具类
 */
public class TokenUtil {
	private static SecureRandom random = null;
	static {
		try {
			random = SecureRandom.getInstance("SHA1PRNG");
		} catch (NoSuchAlgorithmException e) {
		}
	}
	/**
	 * 创建一个安全的随机数组byte[]
	 * 
	 * @return
	 */
	private static byte[] createRandomByte() {
		try {
			byte[] bytes = new byte[1024 / 8];
			random.nextBytes(bytes);
			int count = 10;
			byte[] seed = random.generateSeed(count);
			random = SecureRandom.getInstance("SHA1PRNG");
			random.setSeed(seed);
			SecureRandom random2 = SecureRandom.getInstance("SHA1PRNG");
			random2.setSeed(seed);
			return seed;
		} catch (Exception e) {
			return UUID.randomUUID().toString().getBytes();
		}
	}

	/**
	 * byte[] 转 字符串
	 * 
	 * @param b
	 * @return
	 */
	private static String byte2hex(byte[] b) {
		String hs = "";
		String stmp = "";
		for (int n = 0; n < b.length; n++) {
			stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
			if (stmp.length() == 1)
				hs = hs + "0" + stmp;
			else
				hs = hs + stmp;
		}
		return hs.toUpperCase();
	}

	/**
	 * 获取一个安全的token
	 * 
	 * @return
	 */
	public static String getToken() {
		return byte2hex(createRandomByte());
	}
}
