package com.chinacreator.video.restful.util;

import org.apache.commons.codec.binary.*;
import javax.crypto.spec.*;
import javax.crypto.*;
import java.security.*;
import sun.misc.*;

public class SignUtil
{
    public static String encrypt(final String data, final String key) throws Exception {
        final byte[] bytesKey = Base64.decodeBase64(key);
        final SecretKeySpec secretKeySpec = new SecretKeySpec(bytesKey, "AES");
        final Cipher cipher = Cipher.getInstance("AES");
        cipher.init(1, secretKeySpec);
        final byte[] bytes = cipher.doFinal(data.getBytes("utf-8"));
        return parseByte2HexStr(bytes);
    }
    
    public static String decrypt(final String data, final String key) throws Exception {
        final byte[] bytesKey = Base64.decodeBase64(key);
        final SecretKeySpec secretKeySpec = new SecretKeySpec(bytesKey, "AES");
        final byte[] encryptBytes = parseHexStr2Byte(data);
        final Cipher cipher = Cipher.getInstance("AES");
        cipher.init(2, secretKeySpec);
        final byte[] decryptBytes = cipher.doFinal(encryptBytes);
        return new String(decryptBytes, "UTF-8");
    }
    
    public static String MD5Encrypt(final String str) throws Exception {
        final MessageDigest md5 = MessageDigest.getInstance("MD5");
        final BASE64Encoder base64en = new BASE64Encoder();
        final String newstr = base64en.encode(md5.digest(str.getBytes("utf-8")));
        return newstr;
    }
    
    public static String parseByte2HexStr(final byte[] buf) {
        final StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; ++i) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }
    
    public static byte[] parseHexStr2Byte(final String hexStr) {
        if (hexStr.length() < 1) {
            return null;
        }
        final byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; ++i) {
            final int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            final int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte)(high * 16 + low);
        }
        return result;
    }
    
    public static void main(String[] args) throws Exception {
    	//生成key
		String asckey = "abcdefgh1234ML#@"; //原始KEY，保证16位
		//经BASE64处理后的KEY
		String key = Base64.encodeBase64String(asckey.getBytes());
		//"YWJjZGVmZ2gxMjM0TUwjQA==";
		System.out.println(key);
		//System.out.println(s);
		String usesrid = "18774826258";
		//加密后的手机号码
		String enuserid = SignUtil.encrypt(usesrid, key);
		//4D202FA8C2CEFDC1B3C8C4D0CC4153CF
		System.out.println(enuserid);
		//解密后的手机号码
		String deuserid = SignUtil.decrypt(enuserid, key);
		System.out.println(deuserid);
	}
}
