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

Java 对字符串数据进行MD5/SHA1哈希散列运算

时间:2017-05-11 14:39:05      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:get   哈希   cli   ext   tin   article   ble   plain   tools   

Java对字符串数据进行MD5/SHA1哈希散列运算


[java] view plain copy
 技术分享技术分享
  1. package cn.aibo.test;  
  2.   
  3. import java.security.MessageDigest;  
  4. import java.security.NoSuchAlgorithmException;  
  5.   
  6. public class TestMd5AndSha1 {  
  7.       
  8.     public static String md5(String data) throws NoSuchAlgorithmException {  
  9.         MessageDigest md = MessageDigest.getInstance("MD5");  
  10.         md.update(data.getBytes());  
  11.         StringBuffer buf = new StringBuffer();  
  12.         byte[] bits = md.digest();  
  13.         for(int i=0;i<bits.length;i++){  
  14.             int a = bits[i];  
  15.             if(a<0) a+=256;  
  16.             if(a<16) buf.append("0");  
  17.             buf.append(Integer.toHexString(a));  
  18.         }  
  19.         return buf.toString();  
  20.     }  
  21.       
  22.     public static String sha1(String data) throws NoSuchAlgorithmException {  
  23.         MessageDigest md = MessageDigest.getInstance("SHA1");  
  24.         md.update(data.getBytes());  
  25.         StringBuffer buf = new StringBuffer();  
  26.         byte[] bits = md.digest();  
  27.         for(int i=0;i<bits.length;i++){  
  28.             int a = bits[i];  
  29.             if(a<0) a+=256;  
  30.             if(a<16) buf.append("0");  
  31.             buf.append(Integer.toHexString(a));  
  32.         }  
  33.         return buf.toString();  
  34.     }  
  35.       
  36.     public static void main(String[] args) throws NoSuchAlgorithmException{  
  37.         String data = "abc";  
  38.         //MD5  
  39.         System.out.println("MD5 : "+md5(data));  
  40.         //SHA1  
  41.         System.out.println("SHA1 : "+sha1(data));  
  42.     }  
  43. }  

运算结果

1MD5 : 900150983cd24fb0d6963f7d28e17f72
2SHA1 : a9993e364706816aba3e25717850c26c9cd0d89d





Java 对字符串数据进行MD5/SHA1哈希散列运算

标签:get   哈希   cli   ext   tin   article   ble   plain   tools   

原文地址:http://www.cnblogs.com/jeffen/p/6840562.html

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