package com.reyun.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class ShortUrlGenerator {
	public static String[] beshort(String url, int len) {
		String key = "reyun";
		String[] chars = new String[] { "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", "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"

		};
		// �Դ�����ַ���� MD5 ����
		String sMD5EncryptResult = HashAlgorithms.MD5(key + url);

		String hex = sMD5EncryptResult;

		String[] resUrl = new String[4];
		for (int i = 0; i < 4; i++) {

			String sTempSubString = hex.substring(i * 8, i * 8 + 8);

			long lHexLong = 0x3FFFFFFF & Long.parseLong(sTempSubString, 16);
			String outChars = "";
			for (int j = 0; j < len; j++) {
				long index = 0x0000003D & lHexLong;
				outChars += chars[(int) index];
				lHexLong = lHexLong >> 1;
			}
			resUrl[i] = outChars;
		}
		return resUrl;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		// String sLongUrl = "yybaby" ;
		// String[] aResult;
		// // 
		//
		// for ( int i = 1; i <= 26 ; i++) {
		// aResult = shortUrl (sLongUrl+i);
		// System. out .println( "[" + i + "]-->" + aResult[1]);
		// }

		String dateStr = DateUtil
				.getCurrentDateStr(DateUtil.C_TIME_PATTON_DEFAULT);
		String username = "test@126.com";
		String appname = "hulai";
		// String plattype = "andriod";
		String key = ShortUrlGenerator
				.beshort(username + appname + dateStr, 6)[0];
		// String key = Md5(username+appname+dateStr);
//		System.out.println(key);
		// System.out.println(key.length());
		System.out.println(md5("f7riea"));
		System.out.println(md5("jBqFuE"));
		System.out.println(md5("vERUZY"));
		System.out.println(md5("7rEQU3"));
		System.out.println(md5("qje6NU"));
		System.out.println(md5("eab6MU"));
		System.out.println(md5("uERyne"));
		System.out.println(md5("FQU3mf"));
		
	}

	public static String md5(String plainText) {
		String key = "reyun";
		plainText = plainText + key;
		String result = null;
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(plainText.getBytes());
			byte b[] = md.digest();
			int i;
			StringBuffer buf = new StringBuffer("");
			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if (i < 0)
					i += 256;
				if (i < 16)
					buf.append("0");
				buf.append(Integer.toHexString(i));
			}
			result = buf.toString(); // md5 32bit
			// result = buf.toString().substring(8, 24))); //md5 16bit
			// result = buf.toString().substring(8, 24);
			// //System.out.println("mdt 16bit: " + buf.toString().substring(8,
			// 24));
			// //System.out.println("md5 32bit: " + buf.toString() );
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return result;
	}
}
