package com.ylcm.sys.common;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LoginUtil {

	private static Logger logger = LoggerFactory.getLogger(LoginUtil.class);

	/**
	 * 生成密码
	 * 
	 * @param plainText
	 * @return 生成的密码
	 */
	public static String md5_32(String plainText) {
		String str = null;
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(plainText.getBytes());
			byte b[] = md.digest();

			int i = 0;

			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));
			}
			str = buf.toString();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return str;
	}

	public static String md5_16(String plainText) {
		String str = md5_32(plainText);
		if (str != null) {
			return str.substring(8, 24);
		} else {
			return null;
		}
	}

	/**
	 * 生成session id
	 * 
	 * @param userName
	 *            用户标识
	 * @param password
	 *            用户密码
	 * @return session id
	 */
	public static String encryption(String userName, String password) {
		if ((userName == null) || (password == null)) {
			return null;
		}
		String plainText = userName + "suningjun" + password;
		return md5_32(plainText);
	}

	/**
	 * 获取定长位数随机字符
	 * 
	 * @param length
	 *            位数
	 * @return 定长位数随机字符
	 */
	public static String getRandomString(int length) { // length表示生成字符串的长度
		String base = "abcdefghijklmnopqrstuvwxyz0123456789";
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < length; i++) {
			int number = random.nextInt(base.length());
			sb.append(base.charAt(number));
		}
		return sb.toString();
	}

	/**
	 * 获取定长位数随机数字
	 * 
	 * @param length
	 *            位数
	 * @return 定长位数随机字符
	 */
	public static String getRandomMath(int length) { // length表示生成字符串的长度
		String base = "0123456789";
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < length; i++) {
			int number = random.nextInt(base.length());
			sb.append(base.charAt(number));
		}
		return sb.toString();
	}

	/**
	 * 生成密码
	 * 
	 * @param plainText
	 *            明文
	 * @return 密码
	 */
	public static String generatePassword(String plainText) {

		String password = plainText;

		if (password != null && !("").equals(password)) {
			password = LoginUtil.md5_32(password);
		}
		password = LoginUtil.md5_16(password);
		return password;
	}

	/**
	 * 生成主键
	 * 
	 * @return 主键
	 */
	public static String createPrimaryKey() {
		return UUID.randomUUID().toString();
	}

	/**
	 * 1. byte(8位有符号)的取值范围是 -128-127, char(16位无符号)的取值范围是0-65535;<BR>
	 * 2.如果一个byte对应的十六进制数只有一位前面要用0填充，因为MD5是32位的，达到统一的格式<BR>
	 * 3.0x是十六进制的标示，比如：0xFF表示8位的二进制1111 1111;0x00FF表示16位的二进制0000 0000 1111 1111
	 * */
	public static String getMD5(String str) {
		MessageDigest messageDigest = null;
		try {
			messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.reset();
			messageDigest.update(str.getBytes("UTF-8"));
			byte[] byteArray = messageDigest.digest();
			StringBuffer md5StrBuff = new StringBuffer();
			for (int i = 0; i < byteArray.length; i++) {
				if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) {
					md5StrBuff.append("0").append(
							Integer.toHexString(0xFF & byteArray[i]));
				} else {
					md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
				}
			}
			return md5StrBuff.toString();
		} catch (Exception e) {
			logger.error(e.getMessage());
			return "";
		}
	}

	/**
	 * 解密
	 * 
	 * @param ssoToken
	 *            字符串
	 * @return String 返回加密字符串
	 */
	public static String decrypt(String ssoToken) {
		try {
			String name = new String();
			java.util.StringTokenizer st = new java.util.StringTokenizer(
					ssoToken, "%");
			while (st.hasMoreElements()) {
				int asc = Integer.parseInt((String) st.nextElement()) - 27;
				name = name + (char) asc;
			}

			return name;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 加密
	 * 
	 * @param ssoToken
	 *            字符串
	 * @return String 返回加密字符串
	 */
	public static String encrypt(String ssoToken) {
		try {
			byte[] _ssoToken = ssoToken.getBytes("ISO-8859-1");
			String name = new String();
			// char[] _ssoToken = ssoToken.toCharArray();
			for (int i = 0; i < _ssoToken.length; i++) {
				int asc = _ssoToken[i];
				_ssoToken[i] = (byte) (asc + 27);
				name = name + (asc + 27) + "%";
			}
			return name;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	public static void main(String[] args) {  
        //System.out.println(decrypt("143%128%142%143%91%140%140%73%126%138%136%"));  
          
        //System.out.println(encrypt("frontdev"));  
		
		//System.out.println(generatePassword("a3sda41112123123"));
		System.out.println(generatePassword(getMD5("123456")));
		System.out.println(getMD5("21925584A01196C0DBB822EC14E2AFB7"));
    }  
}