当前位置 : 主页 > 编程语言 > java >

java 接口签名(客户端到服务端)

来源:互联网 收集:自由互联 发布时间:2021-06-28
编码解码工具类 import java.util.HashMap;import java.util.Map;import java.util.regex.Pattern;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;public class MobileTelEncryptor {private static final Log
编码解码工具类
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class MobileTelEncryptor {

	private static final Log log = LogFactory.getLog(MobileTelEncryptor.class);

	private static final String[] cc = new String[] { "M1", "q2", "D5", "G6",
			"S3", "E4", "M9", "K8", "V7", "B4", "H5" };

	private static final String[] dd = new String[] { "0", "1", "2", "3", "4",
			"5", "6", "7", "8", "9", "," };

	private static final Map
 
   map = new HashMap
  
   (); static { for (int i = 0; i < cc.length; i++) { map.put(cc[i], i); } } public static boolean isNumeric(String str) { Pattern pattern = Pattern.compile("[0123456789]*"); return pattern.matcher(str).matches(); } public static boolean isAllow(String str) { Pattern pattern = Pattern.compile("[0123456789,]*"); return pattern.matcher(str).matches(); } //编码 public static String getEncryptString(String srcStr) { if (null == srcStr || "".equals(srcStr.trim()) || "null".equalsIgnoreCase(srcStr.trim())) { return srcStr; } srcStr = srcStr.replaceAll("-", ""); try { if (!isAllow(srcStr)) { // log.info(" EncryptString " + srcStr+ // " is not a number,please check it !"); return srcStr; } char[] ss = srcStr.toCharArray(); StringBuffer sb = new StringBuffer(); for (char s : ss) { // int index = Integer.parseInt(s + ""); int index = 0; for (int i = 0; i < dd.length; i++) { if (dd[i].equals(String.valueOf(s))) { index = i; break; } } sb.append(cc[index]); } return sb.toString(); } catch (Exception e) { return srcStr; } } //解码 public static String getDecryptString(String finalStr) { if (null == finalStr || "".equals(finalStr.trim()) || "null".equalsIgnoreCase(finalStr.trim())) { return finalStr; } try { finalStr = finalStr.replaceAll("-", ""); if (isAllow(finalStr)) { return finalStr; } StringBuffer sb = new StringBuffer(); int len = finalStr.length() / 2; for (int i = 0; i < len; i++) { String key = finalStr.substring(0, 2); int index = map.get(key); sb.append(dd[index]); finalStr = finalStr.substring(2); } return sb.toString(); } catch (Exception e) { return finalStr; } } public static void main(String[] args) { System.err.println(getEncryptString("99178,123")); // B4B4q2K8V7 System.err.println(getDecryptString("B4B4q2K8V7H5q2D5G6")); } } import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class MD5 { /** * Encodes a string * * @param str String to encode * @return Encoded String * @throws Exception */ public static String crypt(String str) { if (str == null || str.length() == 0) { throw new IllegalArgumentException("String to encript cannot be null or zero length"); } StringBuffer hexString = new StringBuffer(); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte[] hash = md.digest(); for (int i = 0; i < hash.length; i++) { if ((0xff & hash[i]) < 0x10) { hexString.append("0" + Integer.toHexString((0xFF & hash[i]))); } else { hexString.append(Integer.toHexString(0xFF & hash[i])); } } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return hexString.toString(); } }
  
 
(安卓)客户端编码鉴权
// Thread
		Thread t = new Thread() {
			@Override
			public void run() {
				// 按数据类型dataKey 获取数据
				Looper.prepare();
				try {
					String versionInfo = IBtspApplication.getInstance()
							.getVersion();
					String model = Build.BRAND + " " + Build.MODEL;
				     //时间戳
                	long timestamp = System.currentTimeMillis();
				     //调用工具类对时间戳加密
                	String timestampStr = MobileTelEncryptor
							.getEncryptString(String.valueOf(timestamp));
					//对参数进行MD5加密
                    String sig = MD5.crypt(mobileNumber + versionInfo + model
							+ timestamp + Consts.SIG_PWD);
				    //调用服务器方法
                	List
 
   accountTokens = accountAuthService
							.accountAuth_v201206(
									AssiConstant.AUTH_GET_AUTH_CODE_REQ_CMD,
									mobileNumber, "", "code", versionInfo,
									model, timestampStr + "_" + sig);
					accountToken = AccountTokenUtils
							.baseAccountToken2AccountToken(accountTokens.get(0));
					if (accountToken != null) {
						h.obtainMessage(RESULT_CODE_SUCCESS).sendToTarget();
						Looper.loop();
						return;
					} else {
						h.obtainMessage(RESULT_CODE_FAIL).sendToTarget();
						Looper.loop();
						return;
					}
				} catch (Exception e) {
					Log.d(TAG, e.getMessage(), e);
					h.obtainMessage(RESULT_CODE_FAIL).sendToTarget();
				}
				ThreadManager.unregister(this);
				Looper.loop();
			}
		};
 
服务端编码鉴权
/**
	 * 鉴权接口签名
	 * 
	 * @param signature
	 * @throws BtirException
	 */
	protected boolean checkSignature(String rightStr, String signature) {

		int delimiter = signature.indexOf("_");    //切割
		if (delimiter < 0) {
			log.error("signature invalid, can't pass.");   //判断签名
			return false;
		}
		String timestampStr = MobileTelEncryptor.getDecryptString(signature     //取出签名时间
				.substring(0, delimiter));
		long clienTimeStamp=Long.valueOf(timestampStr);  //时间转换
		log.info(signature
				.substring(0, delimiter)+":clienTimeStamp:"+clienTimeStamp+"   systemTime:"+System.currentTimeMillis()+" systemTime-clienTimeStamp= "+(System.currentTimeMillis()-clienTimeStamp));
	
    	if(((System.currentTimeMillis()-clienTimeStamp)/1000)>10)//签名时间超过10秒无效
		{
			
			log.error("signature past due, can't pass.");
			return false;
		}
		
		//对签名按照规矩进行加密
		signature = signature.substring(delimiter + 1, signature.length());
		rightStr = rightStr + timestampStr + signaturePassword;

		log.info("rightStr:==========" + rightStr + "============:"
				+ rightStr.length());
		log.info("signature:==========" + signature + "============:"
				+ signature.length());
		String checkSign = MD5.crypt(rightStr);
		log.info("checkSign:==========" + checkSign + "============:"
				+ checkSign.length());

         //比较签名判断参数是否被修改过
		if (!checkSign.equals(signature)) {
			log.error("signature is illegal, can't pass.");
			return false;
		}
		return true;
	}
网友评论