基于MessageDigest的封装

来源:互联网 发布:易我数据恢复免费版 编辑:程序博客网 时间:2024/05/20 06:09

基于MessageDigest的封装

import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.nio.ByteBuffer;import java.nio.channels.FileChannel;import java.nio.charset.Charset;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;/** * Created by zhey on 17-3-20. */public class HashCode {    public static String getHashCode(String filepath, String hashType) {        String hashCode = null;        try {            File file = new File(filepath);            FileInputStream fis = new FileInputStream(file);            MessageDigest md5 = MessageDigest.getInstance(hashType);            ByteBuffer byteBuffer = fis.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length());            md5.update(byteBuffer);            byte[] code = md5.digest();            hashCode = encodeHashCode(code);        } catch (NoSuchAlgorithmException e) {            e.printStackTrace();        } catch (FileNotFoundException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }        return hashCode;    }    public static String getHashCode(File file, String hashType) {        String hashCode = null;        try {            FileInputStream fis = new FileInputStream(file);            MessageDigest md5 = MessageDigest.getInstance(hashType);            ByteBuffer byteBuffer = fis.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length());            md5.update(byteBuffer);            byte[] code = md5.digest();            hashCode = encodeHashCode(code);        } catch (NoSuchAlgorithmException e) {            e.printStackTrace();        } catch (FileNotFoundException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }        return hashCode;    }/*    此处引用他处代码,但是地址忘记了,望作者谅解     */    private static String encodeHashCode(byte[] code) {        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};        char str[] = new char[16 * 2]; // 每个字节用 16 进制表示的话,使用两个字符        int k = 0; // 表示转换结果中对应的字符位置        for (int i = 0; i < 16; i++) { // 从第一个字节开始,对每一个字节,转换成 16 进制字符的转换            byte byte0 = code[i]; // 取第 i 个字节            str[k++] = hexDigits[byte0 >>> 4 & 0xf]; // 取字节中高 4 位的数字转换, >>> 为逻辑右移,将符号位一起右移            str[k++] = hexDigits[byte0 & 0xf]; // 取字节中低 4 位的数字转换        }        return new String(str); // 换后的结果转换为字符串    }}
0 0
原创粉丝点击