其他分享
首页 > 其他分享> > 生成16位卡号和激活码

生成16位卡号和激活码

作者:互联网

生成16位不重复数字,每四位"-"隔开

16位卡号

工具类(规则可自己修改生成)

package com.meditrusthealth.mth.equity.service.util;

import org.apache.commons.lang3.StringUtils;

import java.util.Random;

/**
 * @description: 卡号生成工具
 * @author: Jay
 * @create: 2021-10-22 16:39
 **/
public class CodeNumberUtil {
    private static int i = 0;
    public static final String NUMBERCHAR = "0123456789";
    public static final String ENGILSHCHAR = "QWERTYUIOPASDFGHJKLZXCVBNM1234567890";

    /**
     * Description: 生成条码(卡号)
     */
    public static String getCodeNumber(String prefix) {
        if (!StringUtils.isEmpty(prefix)) {
            //可以修改生成随机数的长度,生成想要的长度的条码
            String num = generateNumString(6);
            String st = prefix + num + getUnixTime();
            return st + getCardCheckCode(st);
        }
        return "prefix不能为空";
    }

    /**
     * 传入一个前缀和一个码。 【根据自己的业务定义】
     *  卡号
     */
    public static String getCodeNumber(String prefix, String code) {
        if (!StringUtils.isEmpty(prefix) && !StringUtils.isEmpty(code)) {
            String st = prefix + code + getUnixTime();
            return st + getCardCheckCode(st);
        }
        return "prefix和code不能为空";
    }

    /**
     * 校验条码是否正确
     */
    public static boolean checkCode(String code) {
        char bit = getCardCheckCode(code.substring(0, code.length() - 1));
        if (bit == 'N') {
            return false;
        }
        return code.charAt(code.length() - 1) == bit;
    }

    /**
     * 从不含校验位的卡号采用 Luhm 校验算法获得校验位
     */
    private static char getCardCheckCode(String nonCheckCodeCardNo) {
        if (nonCheckCodeCardNo == null
                || nonCheckCodeCardNo.trim().length() == 0
                || !nonCheckCodeCardNo.matches("\\d+")) {
            // 如果传的不是数据返回N
            return 'N';
        }
        char[] chs = nonCheckCodeCardNo.trim().toCharArray();
        int luhmSum = 0;
        for (int i = chs.length - 1, j = 0; i >= 0; i--, j++) {
            int k = chs[i] - '0';
            if (j % 2 == 0) {
                k *= 2;
                k = k / 10 + k % 10;
            }
            luhmSum += k;
        }
        return (luhmSum % 10 == 0) ? '0' : (char) ((10 - luhmSum % 10) + '0');
    }

    /***
     * 获取当前系统时间戳 并截取后8位
     */
    private static String getUnixTime() {
        try {
            Thread.sleep(10);// 快速执行时,休眠10毫秒 防止号码重复
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        i++;
        i = i > 100 ? i % 10 : i;
        return ((System.currentTimeMillis() / 100) + "").substring(5)
                + (i % 10);
    }

    /**
     * 生成一个定长的纯数字符串
     */
    private static String generateNumString(int length) {
        StringBuffer sb = new StringBuffer();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            sb.append(NUMBERCHAR.charAt(random.nextInt(NUMBERCHAR.length())));
        }
        return sb.toString();
    }

    /*========================================================================================================*/
    /*===============================================激活码====================================================*/
    /*========================================================================================================*/


    /**
     * Description: 生成激活码(密码)
     */
    public static String getCodeEnglish(String prefix) {
        if (!StringUtils.isEmpty(prefix)) {
            //可以修改生成随机数的长度,生成想要的长度的条码
            String num = generateEngString(2);
            String st = prefix + num + getUnixTime();
            return st + getCardCheckCode(st);
        }
        return "prefix不能为空";
    }
    /**
     * 传入一个前缀和一个码。 【根据自己的业务定义】
     *  激活码
     */
    public static String getCodeEnglish(String prefix, String code) {
        if (!StringUtils.isEmpty(prefix) && !StringUtils.isEmpty(code)) {
            String st = prefix + code + getUnixTime();
            return st + getCardCheckCode(st);
        }
        return "prefix和code不能为空";
    }

    /**
     * 生成一个定长混搭
     */
    private static String generateEngString(int length) {
        StringBuffer sb = new StringBuffer();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            sb.append(ENGILSHCHAR.charAt(random.nextInt(ENGILSHCHAR.length())));
        }
        return sb.toString();
    }


    //测试卡号
//    public static void main(String[] args) {
//
//        try {
//
//            for (int i = 0; i < 1; i++) {
//                // 生成条码
//                String code = getCodeNumber("99");
//                System.out.println(code);
//                // 检验条码
//                System.out.println(checkCode(code));
//            }
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    //测试激活码
//    public static void main(String[] args) {
//        try {
//            for (int i = 0; i < 1; i++) {
//                // 生成条码
//                String code = getCodeEnglish("MX","33");
//                System.out.println(code);
//                // 检验条码
//                System.out.println(checkCode(code));
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
}

用例

 /**
     * 制作卡
     */
    @Transactional
    @Async
    public EquityCardBatchnoResp makeCardAndActivation(EquityCardBatchnoReq equityCardBatchnoReq) throws CommonException {
        /*创建人和创建时间*/
        Date date = new Date();
        //13位的时间戳
        long time = date.getTime();
        EquityCardBatchno equityCardBatchno = new EquityCardBatchno();
        BeanUtils.copyProperties(equityCardBatchnoReq,equityCardBatchno);
        equityCardBatchnoReq.setCreateTime(date);
        EquityCardBatchnoDetail equityCardBatchnoDetail = new EquityCardBatchnoDetail();
        equityCardBatchnoDetail.setBatchNo(String.valueOf(time));
        //卡数
        equityCardBatchno.setBacthCount(2000);
        /*批量制卡*/
        for (int i = 0; i < equityCardBatchno.getBacthCount(); i++) {
            String cardId = CodeNumberUtil.getCodeNumber("99");
            String activationCode = CodeNumberUtil.getCodeEnglish("MD");
            /*卡片校验*/
            boolean checkCode = CodeNumberUtil.checkCode(cardId);
            if (checkCode) {
                /*卡号和激活码*/
                cardId=cardId.replaceAll("(.{4})","$1-");
                cardId = cardId.substring(0, cardId.length() - 1);
                equityCardBatchnoDetail.setCardNo(cardId);
                equityCardBatchnoDetail.setActivationCode(activationCode);
                int saveId = equityCardBatchnoDetailMapper.insert(equityCardBatchnoDetail);
                if (saveId == 1) {
                    log.warn(
                            "{卡号:" + "  " + cardId + "}" + "  " + "保存成功" + "}" +
                                    "{激活码:" + "  " + activationCode + "}" + "  " + "保存成功" + "}"
                    );
                } else {
                    log.warn(
                            "{卡号:" + "  " + cardId + "}" + "  " + "保存失败" +
                                    "{激活码:" + "  " + activationCode + "}" + "  " + "保存失败" + "}"
                    );
                }
            } else {
                log.error(
                        "{卡号:" + "  " + cardId + "}" + "  " + "制卡失败,不符合编卡规则" + "}"
                );
            }
        }
        EquityCardBatchno cardBatchno = equityCardBatchnoMapper.selectById(equityCardBatchno.getId());
        LambdaQueryWrapper<EquityCardBatchnoDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EquityCardBatchnoDetail::getBatchNo,cardBatchno.getBatchNo());
        List<EquityCardBatchnoDetail> list = equityCardBatchnoDetailMapper.selectList(wrapper);
        EquityCardBatchnoResp resp = new EquityCardBatchnoResp();
        BeanUtils.copyProperties(cardBatchno,resp);
        resp.setEquityCardBatchnoDetailList(list);
        log.warn(
                "{本次制卡数量:" + "  " + equityCardBatchnoReq.getBacthCount() + "}" + "  "+"已完成}"
        );
        return resp;
    }

卡号(16位数字,每4位之间用-隔开)

			String cardId = CodeNumberUtil.getCodeNumber("99");
            String activationCode = CodeNumberUtil.getCodeEnglish("MD");
            /*卡号校验*/
            boolean checkCode = CodeNumberUtil.checkCode(cardId);
            /*卡号和激活码*/
            //正则表达式,每四位加"-"
			cardId=cardId.replaceAll("(.{4})","$1-");
			//去除最后一个"-"
            cardId = cardId.substring(0, cardId.length() - 1);
			System.out.println(cardId);

激活码(12位数字+随机字母)

String activationCode = CodeNumberUtil.getCodeEnglish("MD");

标签:code,return,String,16,prefix,激活码,卡号,cardId
来源: https://blog.csdn.net/weixin_45883611/article/details/120993522