[JAVA]MD5加密

 

import java.io.*;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @description:
 * @projectName:HelloWorld
 * @see:PACKAGE_NAME
 * @author:郑晓龙
 * @createTime:2019/5/15 8:48
 * @version:1.0
 */
public class MD5DigestTest {
    public static void main(String[] args) {
        System.out.println(stringMd5Hex("admin"));
        long t1 = System.currentTimeMillis();
        System.out.println(fileMd5Hex("e:/CentOS-7-x86_64-DVD-1810.iso"));
        System.out.println("timing:"+(System.currentTimeMillis()-t1));


    }

    public static String stringMd5Hex(String str) {

        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        BigInteger bigInt = new BigInteger(1, md5.digest(str.getBytes()));
        return bigInt.toString(16);

    }

    public static String fileMd5Hex(String fileName) {

        MessageDigest md = null;
        try (InputStream inputStream = new BufferedInputStream(new FileInputStream(new File(fileName)))) {
            md = MessageDigest.getInstance("MD5");
            byte[] buf = new byte[1024*10];
            int len;
            while ((len = inputStream.read(buf)) != -1) {
                md.update(buf, 0, len);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        BigInteger bigInt = new BigInteger(1, md.digest());
        return bigInt.toString(16);
    }
}

 

posted on 2019-05-15 17:28  郑晓龙  阅读(143)  评论(0编辑  收藏  举报

导航