package com.yice.webadmin.app.util;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Random;

/**
 * 生成工具包
 */
public class GenerateUtil {

    private static final String ALGORITHM = "AES";

    private static final String SECRET_KEY = "This is a secret key!";

    private static final String DIGITAL = "1234567890";

    private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    private static final int KEY_LENGTH = 20;

    private static final int SECRET_KEY_LENGTH = 32;

    /**
     * 生成App_Id
     * @return 随机生成的八位数
     */
    public static Long generateAppId() {
        Random rand = new Random();
        String digits = DIGITAL;
        String code = "";
        for (int i = 0; i < 8; i++) {
            code += digits.charAt(rand.nextInt(digits.length()));
        }
        return Long.parseLong(code);
    }

    /**
     * 生成Api key
     * @return ApiKey
     */
    public static String generateApiKey() {
        Random random = new Random();
        StringBuilder sb = new StringBuilder(KEY_LENGTH);
        for (int i = 0; i < KEY_LENGTH; i++) {
            int index = (int) (random.nextFloat() * CHARACTERS.length());
            sb.append(CHARACTERS.charAt(index));
        }
        return sb.toString();
    }

    /**
     * 生成Secret Key
     * @return SecretKey
     */
    public static String generateSecretKey() {
        try {
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            StringBuilder sb = new StringBuilder(SECRET_KEY_LENGTH);
            for (int i = 0; i < SECRET_KEY_LENGTH; i++) {
                int index = (int) (random.nextFloat() * CHARACTERS.length());
                sb.append(CHARACTERS.charAt(index));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            // 理论上，SHA1PRNG 不应该抛出 NoSuchAlgorithmException，但为了完整性，我们仍然捕获它
            return "";
        }
    }

}
