hex字串與byte數組互轉

來源:互聯網
上載者:User


Toolkit類中的工具方法

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位長的隨機碼// *///static final String secret8 = "Iv}7xlJ^";/** * logger  * @param log 日誌內容 * @param std 是否向控制台列印 */public static void logger(String log, boolean std){OutputStream 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);}///**// * 異或加密// * @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;//}/** * 驗證摘要與資料一致性 * @param digest 摘要 * @param src 資料來源 * @param offset 位移量 * @param len 資料來源長度 * @return true:一致,false:不一致 */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;}/** * 產生包含8位隨機碼+16位MD5的訊息摘要 * @param src 資料來源 * @param offset 位移量 * @param len 長度 * @return 如果執行成功則返回8+16位的位元組摘要,否則返回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字串轉byte數組<br/> * 2個hex轉為一個byte * @param src * @return */public static byte[] hex2Bytes1(String 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]<='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字串轉byte數組<br/> * 2個hex轉為一個byte * @param src * @return */public static byte[] hex2Bytes(String 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數組轉hex字串<br/> * 一個byte轉為2個hex字元 * @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 new String(res);      } /** * 產生安全簽字 * @param src * @return */public static String signature(String src){final String secret8 = "Iv}7xlJ^";return sha1Hex(secret8+src); }/** * 返回16進位sha-1加密後資訊 * @param btInput * @return */public static String sha1Hex(byte[] btInput){final char 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();// 把密文轉換成十六進位的字串形式            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 "";}}/** * 返回16進位sha-1加密後資訊 * @param src * @return */public static String sha1Hex(String src){return sha1Hex(src.getBytes());}}


測試類別:

      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---");}





相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.