Hex string and byte array to go with each other

Source: Internet
Author: User
Tags dateformat log log md5


Tool methods in the Toolkit class

Package org.sl.util;
Import Java.io.File;
Import Java.io.FileOutputStream;
Import Java.io.OutputStream;
Import Java.security.MessageDigest;
Import Java.text.SimpleDateFormat;
Import Java.util.Date;

Import Java.util.Random;
	public class Toolkit {public static final File logFile = new File (".", "App_sl.log");
public static final SimpleDateFormat DateFormat = new SimpleDateFormat ("[Yyyy/mm/dd HH:mm:ss]");
	
	
	/**//* 8-bit long random code////static final String Secret8 = "iv}7xlj^"; /** * Logger * @param log log content * @param std to the console print/public static void logger (String log, Boolean std) {Ou
		Tputstream out = null;
		
		String dt = null;
			
			try{dt = Dateformat.format (new Date ());
			
			if (STD) System.out.println (dt+log);
			if (Logfile.length () >1024*1024*20) {logfile.delete ();			
			out = new FileOutputStream (LogFile, true);
			Out.write (Dt.getbytes ());
			Out.write (Log.getbytes ());
			Out.write (' \ n ');
		Out.flush (); }catch (Exception ex) {}finally{
			try {if (null!=out) out.close ();		
		catch (Exception e) {}}}/** * logger * @param log/public static void logger (String log) {
	Logger (log, false);  }///**//* XOR///* @param src//* @return////public static byte[] XOR (byte[] src) {//byte[] res = new
Byte[src.length];
for (int i=0; i<src.length; i++) {//Res[i] = (byte) (Src[i] ^ secret80[i]);//}////return res; /** * Validation Summary and data consistency * @param Digest Summary * @param src data source * @param offset offset * @param len Data source length * @return True: Consistent, false: inconsistent */public static Boolean checkdigest (Byte[] digest, byte[] src, int offset, int len) {Boolean OK =
		False
		Final int secret_size = 8;		
		
		byte[] sign = new BYTE[SECRET_SIZE+16];
			try{System.arraycopy (Digest, 0, sign, 0, secret_size);
			MessageDigest MD5 = messagedigest.getinstance ("MD5");
			Md5.update (digest,0,secret_size);
			Md5.update (Src,offset,len); Md5.digest (sign,secret_size,sign.length-secret_size);
		OK = Toolkit.bytes2hex (digest). Equals (Toolkit.bytes2hex (sign));
		}catch (Exception ex) {ex.printstacktrace ();
	return OK; /** * Generates a message digest containing 8-bit random code + 16-bit MD5 * @param src data source * @param offset offset * @param len length * @return If successful, returns the word 8+16 bit
		Section Summary, otherwise return NULL */public static byte[] Digest (byte[] src, int offset, int len) {final int secret_size = 8;
		Byte[] Secret = new Byte[secret_size];		
		byte[] sign = new BYTE[SECRET_SIZE+16];		
		
		New Random (). Nextbytes (Secret);
			try{system.arraycopy (Secret, 0, sign, 0, secret_size);
			MessageDigest MD5 = messagedigest.getinstance ("MD5");
			Md5.update (secret);
			Md5.update (Src,offset,len);
		Md5.digest (sign,secret_size,sign.length-secret_size);
			}catch (Exception ex) {ex.printstacktrace ();
		sign = null;
	return sign; /** * Hex string to byte array <br/> * 2 hex converted to a byte * @param src * @return/public static byte[] Hex2bytes1 (S
Tring src) {byte[] res = new Byte[src.length ()/2];		char[] CHS = Src.tochararray ();

		Int[] B = new int[2]; for (int i=0,c=0; i<chs.length; i+=2,c++) {for (int j=0; j<2; J + +) {if (chs[i+j]>= ' 0 ' && chs[i+j]&
				lt;= ' 9 ') {b[j] = (chs[i+j]-' 0 ');
				}else if (chs[i+j]>= ' a ' && chs[i+j]<= ' F ') {b[j] = (chs[i+j]-' a ' +10);
				}else if (chs[i+j]>= ' a ' && chs[i+j]<= ' F ') {b[j] = (chs[i+j]-' a ' +10);
			}} B[0] = (b[0]&0x0f) <<4;
			B[1] = (b[1]&0x0f);
		RES[C] = (byte) (b[0] | b[1]);
	return res; /** * Hex string to byte array <br/> * 2 hex converted to a byte * @param src * @return/public static byte[] Hex2bytes (St		
		Ring src) {byte[] res = new Byte[src.length ()/2];
		char[] CHS = Src.tochararray ();
		for (int i=0,c=0; i<chs.length; i+=2,c++) {res[c] = (byte) (Integer.parseint (New String (chs,i,2), 16);
	return res; /** * byte array hex string <br/> * A byte to 2 hex characters * @param src * @return/public static string BYTES2HEx (byte[] src) {char[] res = new CHAR[SRC.LENGTH*2];  
        Final char hexdigits[]={' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ', ' A ', ' B ', ' C ', ' D ', ' E ', ' F '};  
            for (int i=0,j=0; i<src.length; i++) {res[j++] = Hexdigits[src[i] >>>4 & 0x0f];  
        Res[j++] = Hexdigits[src[i] & 0x0f];  
    Return to New String (RES);  /** * Generate secure Signature * @param src * @return/public static string signature (string src) {final String secret8 =
		"iv}7xlj^"; 
	Return Sha1hex (SECRET8+SRC); /** * Returns 16 sha-1 encrypted message * @param btinput * @return/public static String Sha1hex (byte[] btinput) {final C
		Har hexdigits[]={' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ', ' A ', ' B ', ' C ', ' D ', ' E ', ' F '};
			try {messagedigest mdinst = messagedigest.getinstance ("SHA-1");
			Mdinst.update (Btinput);
			byte[] MD = Mdinst.digest ();
            Converts cipher text into a 16-binary string form int j = md.length; Char str[] = new CHAR[J * 2];
                for (int i=0,k=0 i < J; i++) {byte byte0 = md[i];
                str[k++] = hexdigits[byte0 >>> 4 & 0xf];
            str[k++] = hexdigits[byte0 & 0xf];            
		return new String (str);
		catch (Exception e) {return ""; }/** * Returns 16 sha-1 encrypted message * @param src * @return/public static String Sha1hex (String src) {return sha1h
	Ex (Src.getbytes ());
 }	
}


Test class:

      static void T16 () {
		byte[] src = new byte[1024];
		New Random (). nextbytes (SRC);
		Byte[] Digest = Digest (src,0,src.length);		digest[3]= ' 2 ';
		System.out.println (Checkdigest (Digest, Src,0,src.length));
	}

      static void T15 () {
		byte[] src = new byte[10];
		New Random (). nextbytes (SRC);		byte[] src = "12345qwert". GetBytes ();
		for (byte b:src) {
			System.out.print ((byte) B + "");
		}
		SYSTEM.OUT.PRINTLN ("----src---");
		String hex = Toolkit.bytes2hex (src);
		System.out.println (hex);
		
		src = toolkit.hex2bytes1 (hex);
		for (byte b:src) {
			System.out.print (b + "");
		}
		SYSTEM.OUT.PRINTLN ("----src---");
		Hex = Toolkit.bytes2hex (src);
		System.out.println (hex);
		
		src = toolkit.hex2bytes1 (hex);
		for (byte b:src) {
			System.out.print (b + "");
		}
		SYSTEM.OUT.PRINTLN ("----src---");
	}





Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.