Hash函數和消息摘要算法


一、Hash函數

  哈希函數就是能將任意長度的數據映射為固定長度的數據的函數。哈希函數返回的值被叫做哈希值、哈希碼、散列,或者直接叫做哈希。

二、消息摘要

    將長度不固定的消息(message)作為輸入參數,運行特定的Hash函數,生成固定長度的輸出,這個輸出就是Hash,也稱為這個消息的消息摘要(Message Digest)

      信息摘要算法是hash算法的一種,具有以下特點:

  • 無論輸入的消息有多長,計算出來的消息摘要的長度總是固定的,計算出的結果越長,一般認為該摘要算法越安全,MD5 128位 SHA-1 160位
  • 輸入的消息不同,產生的消息摘要必不同,輸入的消息相同,產生的消息摘要一定是相同的
  • 單向不可逆

三、MessageDigest

  java中通過MessageDigest來為程序提供消息摘要算法的功能,例如md5 和sha,這個經常會使用的到,這里就不多解釋了

標記解釋

  1. 通過入參的算法名獲取MessageDigest實例,入參例如:MD2  MD5  SHA-1  SHA-256  SHA-384  SHA-512
  2. 指定的算法摘要的提供者,可通過Security.getProviders() 方法獲取
  3. 使用指定的字節數組更新摘要
  4. 完成hash計算,只調用一次,在調用 digest()方法之后,MessageDigest 對象被重新設置成其初始狀態
  5. 重置摘要

四、使用

  由於commons-codec包中已經封裝好了一些使用的方法,引入依賴,直接調用即可

4.1、依賴

      <dependency>
          <groupId>commons-codec</groupId>
          <artifactId>commons-codec</artifactId>
          <version>1.4</version>
      </dependency>

4.2、工具類

package com.treebear.starwifi.common.util;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @author DUCHONG
 * @since 2018-05-02 9:18
 **/
public class EncryptionUtils {

    public static String base64Encode(String data){

        return Base64.encodeBase64String(data.getBytes());

    }

    public static byte[] base64Decode(String data){

        return Base64.decodeBase64(data.getBytes());

    }

    public static String md5(String data) {

        return DigestUtils.md5Hex(data);

    }

    public static String sha1(String data) {

        return DigestUtils.shaHex(data);

    }

    public static String sha256Hex(String data) {

        return DigestUtils.sha256Hex(data);

    }

    public static String getMD5File(File file){
        FileInputStream fis=null;
        try {
            fis=new FileInputStream(file);
            return DigestUtils.md5Hex(fis);
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            if(fis != null){
                try {
                    fis.close();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }


    public static void main(String[] args) {


        //long start= System.currentTimeMillis();

        System.out.println(getMD5File(new File("F:\\temp\\WEB-INF.zip")));
        System.out.println(getMD5File(new File("F:\\temp2\\WEB-INF.zip")));


        //long end=System.currentTimeMillis();

        //System.out.println("共耗時:"+(float)(end-start)/1000+"s");
    }
}

  

 


免責聲明!

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



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