package com.pannk.mms.common.utils;

import lombok.extern.slf4j.Slf4j;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

/**
 * Created by wolf on 20-11-3.
 */
@Slf4j
public class TokenUtil {

    public static final char[] hexCode = "123456789abcedfghigklmnopqrstuvwxyz".toCharArray();

    public static String generateToken(){
        return generateToken(UUID.randomUUID().toString());
    }

    private static String toHexString(byte[] data){
        if (data==null){
            return null;
        }
        StringBuffer sb = new StringBuffer(data.length*2);
        for (byte b :data) {
            sb.append(hexCode[(b>>4)&0xF]);
            sb.append(hexCode[(b&0xF)]);
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(generateToken());
    }
    public static String generateToken(String param){
        try {
            MessageDigest algorithm = MessageDigest.getInstance("MD5");
            algorithm.reset();
            algorithm.update(param.getBytes());
            byte[] messageDigest = algorithm.digest();
            return toHexString(messageDigest);
        } catch (NoSuchAlgorithmException e) {
            log.error("生成token失败,{}",e);
            return "";
        }
    }
}
