码迷,mamicode.com
首页 > 编程语言 > 详细

摘要算法测试MD5或SHA-1

时间:2016-11-29 19:01:25      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:system   instance   als   author   工具   name   16进制   catch   append   

package com.fenghao.other;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 
 * <P>摘要工具类使用MD5或SHA-1摘要算法</P>
 * @ClassName: MessageDigestUtils
 * @author 冯浩  2016年11月29日 下午3:15:54
 * @see TODO
 */
public class MessageDigestUtils {
	
	public  String digestMessage(String context,String hashType) throws NoSuchAlgorithmException{
		MessageDigest in = MessageDigest.getInstance(hashType);
		byte[] digest = in.digest(context.getBytes());
		return bytes2Hex(digest);
	}
	
	private  String bytes2Hex(byte[] bytes){
		StringBuilder str=new StringBuilder();
		for (int i = 0; i < bytes.length; i++) {
			 byte b=bytes[i];
			 boolean negative=false;//判断正负
			 if(b<0) negative=true;
			 int line = Math.abs(b);//取绝对值
			 if(negative) line=line|0x80; //0x代表十六进制 8*16=128 二进制表示:10000000 负负得正   最高位的负号变成数值进行计算
			 String tmp = Integer.toHexString(line&0xFF);
			 if(tmp.length()==1){
				 str.append("0");
			 }
			 str.append(tmp.toLowerCase());
		}
		return str.toString();
	}
	/**
	 * 
	 * <p>方法测试</p>
	 * <p>Description: TODO</p>
	 * @author 冯浩  2016年11月29日 下午3:41:13
	 */
	@org.junit.Test
	public void Test(){
		int a=3;//3
		int b=-3;//3
		int c=128;//128
		int d=-128;//128
		int e=129;//129
		int f=-129;//129 
		int i = Math.abs(-199);//取绝对值
		int n=d|0x80;
		System.out.println("\n n is "+n);
	}
	
	public static void main(String[] args) {
		MessageDigestUtils message=new MessageDigestUtils();
		String context="fenghao";
		try {
			String result = message.digestMessage(context, "MD5");
			System.out.println("\n result is "+result);
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

 使用MD5摘要后对字节数组进行16进制编码!

摘要算法测试MD5或SHA-1

标签:system   instance   als   author   工具   name   16进制   catch   append   

原文地址:http://www.cnblogs.com/nihaofenghao/p/6114594.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!