Java 消息摘要 散列 MD5 SHA

时间:2021-05-18 04:37:26
package xxx.common.util;

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

/**
 * 消息摘要 散列
 * Created by windwant on 2016/12/14.
 */
public class MessageDigestUtil {

    public static void main(String[] args) {
        System.out.println(md5("lilei"));
        System.out.println(sha("lilei"));
    }

    private static String md5(String data){
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(data.getBytes());
            return  new BigInteger(1, md.digest()).toString(16);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static String sha(String data){
        try {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(data.getBytes());
            return  new BigInteger(1, md.digest()).toString(16);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

}