JAVA訊息摘要用處__JAVA

來源:互聯網
上載者:User

網路計算環境中很多時候需要對檔案進行訊息摘要計算,防止檔案被篡改,校正檔案是否被修改過,JDK本身提供了訊息摘要演算法,使用起來相當方便,主要用到安全摘要計算類

java.security.MessageDigest,如下:

package com.test.b;import java.io.BufferedInputStream;import java.io.FileInputStream;import java.io.InputStream;import java.security.MessageDigest;public class MessageDigestTest {    /**     * @param args     * @throws Exception      */    public static void main(String[] args) throws Exception {        String file = "mm.txt";  //該檔案為需要進行摘要計算的檔案        comMessDigest(file,"SHA-1");        comMessDigest(file,"MD5");    }        /**     *      * @param name  檔案名稱     * @param md    摘要演算法     * @throws Exception     */    public static void comMessDigest(String name,String md) throws Exception{        MessageDigest digest = MessageDigest.getInstance(md);        InputStream in = new BufferedInputStream(new FileInputStream(name));                int ch;        while((ch = in.read())!=-1){            //用指定位元組更新摘要            digest.update((byte)ch);        }        in.close();        //完成散列摘要計算        byte[] hash = digest.digest();        printResult(hash);    }        /**     * 列印摘要結果     * @param scoure     */    public static void printResult(byte[] scoure){        StringBuilder builder = new StringBuilder();        for(byte c: scoure){            builder.append((int)c);        }        System.out.println(builder.toString());    }}

結果如下:

682289988-127418543-1277977120-372-125-36-5364105-96-19-641210641-72-77-6282-8-67-611221005




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.