MessageDigest的功能及用法(加密解密) SHA _ MD5


MessageDigest的功能及用法(加密解密)

MessageDigest 加密和解密2

 

 

 

 
MessageDigest的功能及用法
MessageDigest 類為應用程序提供信息摘要算法的功能,如 MD5 或 SHA 算法。信息摘要是安全的單向哈希函數,它接收任意大小的數據,並輸出固定長度的哈希值。
 
MessageDigest 對象開始被初始化。該對象通過使用 update()方法處理數據。任何時候都可以調用 reset()方法重置摘要。一旦所有需要更新的數據都已經被更新了,應該調用digest() 方法之一完成哈希計算。
 
對於給定數量的更新數據,digest 方法只能被調用一次。在調用 digest 之后,MessageDigest 對象被重新設置成其初始狀態。
 
1、 public  static  MessageDigest getInstance(String algorithm)
                                  throws NoSuchAlgorithmException
    返回實現指定摘要算法的 MessageDigest 對象。
    algorithm - 所請求算法的名稱
2、 public  static  MessageDigest getInstance(String algorithm,
                                         String provider)
                                  throws NoSuchAlgorithmException,
                                         NoSuchProviderException
   返回實現指定摘要算法的 MessageDigest 對象。
   algorithm - 所請求算法的名稱
   provider - 提供者的名稱。
3、 public  void  update( byte [] input)
   使用指定的  byte  數組更新摘要。
4、 public  byte [] digest()
   通過執行諸如填充之類的最終操作完成哈希計算。在調用此方法之后,摘要被重置。
5、 public  static  boolean isEqual( byte [] digesta,
                               byte [] digestb)
比較兩個摘要的相等性。做簡單的字節比較。
  
 
  
 
注意:Provider可以通過 Java.security.Security.getProviders() 方法獲取已注冊提供者列表。比較常用的有“SUN”
 
SUN提供的常用的算法名稱有:MD2
MD5
                         SHA-1
                         SHA-256
                         SHA-384
                         SHA-512
 
  
 
Code舉例:
 
import java.security.*;
public  class  myDigest {
   public  static  void  main(String[] args)  {
     myDigest my= new  myDigest();
     my.testDigest();
   }
   public  void  testDigest()
   {
    try  {
      String myinfo= "我的測試信息" ;
     //java.security.MessageDigest alg=java.security.MessageDigest.getInstance("MD5");
       java.security.MessageDigest alga=java.security.MessageDigest.getInstance( "SHA-1" );
       alga.update(myinfo.getBytes());
       byte [] digesta=alga.digest();
       System. out .println( "本信息摘要是:" +byte2hex(digesta));
       //通過某中方式傳給其他人你的信息(myinfo)和摘要(digesta) 對方可以判斷是否更改或傳輸正常
       java.security.MessageDigest algb=java.security.MessageDigest.getInstance( "SHA-1" );
       algb.update(myinfo.getBytes());
       if  (algb.isEqual(digesta,algb.digest())) {
          System. out .println( "信息檢查正常" );
        }
        else
         {
           System. out .println( "摘要不相同" );
          }
    }
    catch  (java.security.NoSuchAlgorithmException ex) {
      System. out .println( "非法摘要算法" );
    }
   }
   public  String byte2hex( byte [] b)  //二行制轉字符串
     {
      String hs= "" ;
      String stmp= "" ;
      for  ( int  n=0;n<b.length;n++)
       {
        stmp=(java.lang.Integer.toHexString(b[n] & 0XFF));
        if  (stmp.length()==1) hs=hs+ "0" +stmp;
        else  hs=hs+stmp;
        if  (n<b.length-1)  hs=hs+ ":" ;
       }
      return  hs.toUpperCase();
     }
}

  

  
 
 
« 上一篇:  js編寫時間選擇框
» 下一篇:  MessageDigest 加密和解密2
 
 
________________________________________________________________________________________________________

Java MD5Utils

 

Java MD5Utils 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
/**
  * <html>
  * <body>
  *  <P> Copyright 1994 JsonInternational</p>
  *  <p> All rights reserved.</p>
  *  <p> Created on 19941115</p>
  *  <p> Created by Jason</p>
  *  </body>
  * </html>
  */
package  cn.ucaner.alpaca.framework.utils.encrypt;
import  java.math.BigInteger;
import  java.security.MessageDigest;
import  java.security.NoSuchAlgorithmException;
 
import  org.apache.commons.lang3.StringUtils;
 
/**
* @Package:cn.ucaner.alpaca.framework.utils.encrypt  
* @ClassName:MD5Utils  
* @Description:   <p> MD5加密工具    By Jason </p>
* @Author: - Jason  
* @CreatTime:2018年5月24日 下午9:40:31  
* @Modify By:  
* @ModifyTime:  2018年5月24日
* @Modify marker:  
* @version    V1.0
  */
class  MD5Utils {
     protected  final  static  String MD5_KEY =  "MD5" ;
     
     protected  final  static  String SHA_KEY =  "SHA1" ;
     
     /**
      * @param value
      * @param key
      * @return
      */
     protected  static  String encrypt(String value,String key) {
         try  {
             // 拿到一個MD5轉換器(如果想要SHA1參數換成”SHA1”)
             MessageDigest messageDigest = MessageDigest.getInstance(key);
             // 輸入的字符串轉換成字節數組
             byte [] inputByteArray = value.getBytes();
             // inputByteArray是輸入字符串轉換得到的字節數組
             messageDigest.update(inputByteArray);
             // 轉換並返回結果,也是字節數組,包含16個元素
             byte [] resultByteArray = messageDigest.digest();
             // 字符數組轉換成字符串返回
             return  byteArrayToHex(resultByteArray);
         catch  (NoSuchAlgorithmException e) {
             return  null ;
         }
     }
 
     /**
      * 字節數組轉換為hex
      * @param byteArray
      * @return
      */
     private  static  String byteArrayToHex( byte [] byteArray) {
 
         // 首先初始化一個字符數組,用來存放每個16進制字符
         char [] hexDigits = {  '0' '1' '2' '3' '4' '5' '6' '7' '8' '9' , 'A' 'B' 'C' 'D' 'E' 'F'  };
         // new一個字符數組,這個就是用來組成結果字符串的(解釋一下:一個byte是八位二進制,也就是2位十六進制字符(2的8次方等於16的2次方))
         char [] resultCharArray =  new  char [byteArray.length *  2 ];
         // 遍歷字節數組,通過位運算(位運算效率高),轉換成字符放到字符數組中去
         int  index =  0 ;
         for  ( byte  b : byteArray) {
             resultCharArray[index++] = hexDigits[b >>>  4  0xf ];
             resultCharArray[index++] = hexDigits[b &  0xf ];
         }
         // 字符數組組合成字符串返回
         return  new  String(resultCharArray);
     }
     /**
      * 獲得16位的加密字符
      * @param str
      * @return
      * @throws NoSuchAlgorithmException
      */
     public  static  String getMd5String16(String str)  throws  NoSuchAlgorithmException {
         String md5str = getMd5String32(str).substring( 8 );
         return  md5str.substring( 0 , md5str.length() -  8 );
     }
 
     /**
      * 獲得24位的MD5加密字符
      * @param str
      * @return
      * @throws NoSuchAlgorithmException
      */
     public  static  String getMd5String24(String str)  throws  NoSuchAlgorithmException {
 
         String md5str = getMd5String32(str).substring( 4 );
         return  md5str.substring( 0 , md5str.length() -  4 );
     }
 
     /**
      * 獲得32位的MD5加密算法
      * @param str
      * @return
      * @throws NoSuchAlgorithmException
      */
     public  static  String getMd5String32(String str)  throws  NoSuchAlgorithmException {
         MessageDigest md = MessageDigest.getInstance( "MD5" );
         md.update(str.getBytes());
         byte  b[] = md.digest();
         int  i;
         StringBuffer buf =  new  StringBuffer();
         for  ( int  offset =  0 ; offset < b.length; offset++) {
             i = b[offset];
 
             if  (i <  0 )
                 i +=  256 ;
 
             if  (i <  16 )
                 buf.append( "0" );
 
             buf.append(Integer.toHexString(i));
         }
         return  buf.toString();
     }
 
     /**
      * 獲取MD5密碼
      * @param password
      * @param salt
      * @return
      * @throws NoSuchAlgorithmException
      */
     public  static  String getMD5Pwd(String password, String salt)  throws  NoSuchAlgorithmException {
         String result =  null ;
         if  (StringUtils.isNotBlank(salt)) {
             result = getMD5(getMD5(password) + salt);
         else  {
             result = getMD5(password);
         }
         return  result;
     }
 
     /**
      * 獲取MD5加密數據
      * @param input
      * @return
      * @throws NoSuchAlgorithmException
      */
     public  static  String getMD5(String input)  throws  NoSuchAlgorithmException {
         String result = input;
         if  (input !=  null ) {
             MessageDigest md = MessageDigest.getInstance( "MD5" );  //or "SHA-1"
             md.update(input.getBytes());
             BigInteger hash =  new  BigInteger( 1 , md.digest());
             result = hash.toString( 16 );
             while  (result.length() <  32 ) { //40 for SHA-1
                 result =  "0"  + result;
             }
         }
         return  result;
     }
 
     /**
      * For test by Jason
      */
     public  static  void  main(String[] args) {
         try  {
             System.out.println(getMd5String16( "Jason" ));  //829018f9dbd65fb8
         catch  (NoSuchAlgorithmException e) {
             e.printStackTrace();
         }
     }
}

  

 

 
分類:  JavaUtils
 
 
 
« 上一篇:  Java Base64Utils
» 下一篇:  Java 獲取客服端ip地址
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM