package com.example.gmalpha_flutter.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

public class UploadMD5Key {
    private String myValue = "";
    private String endValue = "";
    private String myKey = "";
    public static String getKey(){
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd/HHmm");
        String t=format.format(new Date());
        long timeStamp = System.currentTimeMillis();
        String str = timeStamp+getRandomString();
        String myValue = "";
        String endValue = "";
        try {
            myValue = md5(str);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        endValue = myValue.substring(0,12);

        return t+"/"+endValue;
    }

    public static String getRandomString(){
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        int randomNum;
        char randomChar;
        Random random = new Random();
        // StringBuffer类型的可以append增加字符
        StringBuffer str = new StringBuffer();

        for (int i = 0; i < 32; i++) {
            // 可生成[0,n)之间的整数，获得随机位置
            randomNum = random.nextInt(base.length());
            // 获得随机位置对应的字符
            randomChar = base.charAt(randomNum);
            // 组成一个随机字符串
            str.append(randomChar);
        }
        return str.toString();
    }

    public  static String md5(String data) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(data.getBytes());
        StringBuffer buf = new StringBuffer();
        byte[] bits = md.digest();
        for(int i=0;i<bits.length;i++){
            int a = bits[i];
            if(a<0) a+=256;
            if(a<16) buf.append("0");
            buf.append(Integer.toHexString(a));
        }
        return buf.toString();
    }


}
