十六进制编码求异或

如同消息头加密一样:对两字符串先进行转码,再求两转码后的异或,生成新的十六进制编码:

初步处理如下:

package com.foxconn;

import java.text.ParseException;

public class Aa {
	/*
	 * @author Yujie_Li
	 */
	private static String hexString = "0123456789ABCDEF"; 
	
    public static void main(String args[]) throws ParseException{
     	 String code1 = encode("9CE00K00781065");
     	 String code2 = encode("TOX$123FTOX$321");
     	 System.out.println(code1);
     	 System.out.println(code2);
     	byte [] a = code1.getBytes();
     	byte [] b = code2.getBytes();
     	byte [] c = new byte[code1.length()];
     	//byte类型需要先转化成字符数组,然后才能转化成字符串
     	StringBuffer sb = new StringBuffer();
     	String ret = "";
	 	for(int i =0;i>" + hex);
	 		c[i] = (byte) ((a[i]& 0xFF)^(b[i]& 0xFF));
	 		System.out.println(i+"--------"+Integer.toBinaryString(a[i])+
	 				"-------"+Integer.toBinaryString(b[i])+"----"+Integer.toBinaryString((a[i]& 0x0f)^(b[i]& 0x0f)));
	 		sb.append(c[i]&0xFF);
	 	 }
	     String code3 = sb.toString();
	 	 System.out.println(code3);
	 	 System.out.println(ret);
    }
    
    public static String encode(String str) {
    	   // 根据默认编码获取字节数组
    	   byte[] bytes = str.getBytes();
    	   String strs = "";
    	   // 将字节数组中每个字节拆解成2位16进制整数
    	   for (int i = 0; i < bytes.length; i++) {
    	   // 高四位
    	    strs += hexString.charAt((bytes[i] & 0xf0) >> 4);
    	    //System.out.println(i+"--"+bytes[i]+"----"+(bytes[i] & 0xf0)+"----"+hexString.charAt((bytes[i] & 0xf0) >> 4));
    	    // 低四位
    	    strs += hexString.charAt((bytes[i] & 0x0f) >> 0);
    	   }
    	   return strs;
    	}
}

 测试发现如果转码后求异或后某些超过16进制基数的无法得到正确解。特做如下修改:

package com.foxconn;
import java.text.ParseException;


public class Aa {
	private static String hexStr = "0123456789ABCDEF"; 
    public static void main(String args[]) throws ParseException{
    	
 	   String code1 = encode("9CE00K00781065");
     	   String code2 = encode("TOX$123FTOX$321");
 	   System.out.println(code1);
 	   System.out.println(code2);
 	   System.out.println("7F0C1D14017903767F6814010203");
 	   
 	    String result ="";
 	   for(int i=0; i> 4);
    	   // System.out.println(i+"--"+bytes[i]+"----"+(bytes[i] & 0xf0)+"----"+hexString.charAt((bytes[i] & 0xf0) >> 4)+"---"+hexString.charAt((bytes[i] & 0x0f) >> 0));
    	    //取得低四位
    	    strs += hexStr.charAt((bytes[i] & 0x0f) >> 0);
    	   }
    	   return strs;
    	}
}

 即可

你可能感兴趣的:(学习笔记)