/**
 * 
 */
package com.duiba.tuia.youtui.web.tool;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** 
 * ClassName:BehaviorCipher.java <br/>
 * @author  gey 
 * @date 创建时间：2016年11月18日 上午10:33:16 
 * @version 1.0 
 * @parameter  
 * @since   JDK 1.6
 */
public class BehaviorCipher {
    private static Logger log = LoggerFactory.getLogger(BehaviorCipher.class); //Test为具体的类名
	static String cycle="TnBCDghijLMGPtUVklmzA+pqQocNORFd=efwxyabHIJKSY/rsuvEWXZ";
	
	private BehaviorCipher(){
	    
	}
	
	static String encode(String content,String key){
		String cont=new Base64().encodeToString(content.getBytes());
		int offset=key.charAt(key.length()-1);
		char[] result=new char[cont.length()];
		for(int i=0;i<cont.length();i++){
			char c=cont.charAt(i);
			int index=cycle.indexOf(c);
			if(index!=-1){
				int newindex=(index+offset)%cycle.length();
				result[i]=cycle.charAt(newindex);
			}else{
				result[i]=c;
			}
		}
		String ret= new String(result);
		String md5="";
		try {
			md5=MD5.md5(ret);
		} catch (Exception e) {
		    log.error("",e);
		}
		String sub=md5.substring(md5.length()-5);
		return ret+sub;
	}
	
    static String decode(String content,String key){
		String sub=content.substring(content.length()-5);
		String con=content.substring(0, content.length()-5);
		
		String md5=null;
		try {
			md5 = MD5.md5(con);
		} catch (Exception e) {
		    log.error("",e);
		}
		
		if(md5==null || !md5.endsWith(sub)){
			return null;
		}
		
		int offset=key.charAt(key.length()-1);
		char[] result=new char[con.length()];
		for(int i=0;i<con.length();i++){
			char c=con.charAt(i);
			int index=cycle.indexOf(c);
			if(index!=-1){
				int newindex=(index-offset)%cycle.length();
				if(newindex<0){
					newindex=newindex+cycle.length();
				}
				result[i]=cycle.charAt(newindex);
			}else{
				result[i]=c;
			}
		}
		try {
			return new String(new Base64().decode(new String(result)));
		} catch (Exception e) {
			log.error("",e);
		}
		return null;
	}
}
