RSA统一签名验证

/**
 * <h2>RSA池化</h2>
 **/
public class RsaPoolExecutor {


    private final BlockingQueue<RSA> workQueue;


    /**
     * 最大数
     */
    private final int maximumPoolSize;

    private final ReentrantLock lock = new ReentrantLock();

    private final Condition notEmpty = lock.newCondition();

    private final Condition notFull = lock.newCondition();


    public RsaPoolExecutor(int maximumPoolSize,  BlockingQueue<RSA> workQueue) {
        if (maximumPoolSize <= 0)
            throw new IllegalArgumentException();
        if (workQueue == null)
            throw new NullPointerException();

        this.maximumPoolSize = maximumPoolSize;
        this.workQueue = workQueue;
        new Thread(new Watchdog()).start();
    }


    /**
     * 获取公私钥对。
     *
     * @return RSAEntry
     */
    public AsymmetricEntry<String, String> takeAsymmetricEntry() {
        lock.lock();
        RSA rsa;
        try {
            while (this.workQueue.isEmpty()) {
                notFull.signal();
                log.info("RSA池已经空了," + Thread.currentThread().getName() + "等待!");
                notEmpty.await();

            }
            notFull.signal();
            rsa = workQueue.take();
        } catch (InterruptedException e) {
            rsa = new RSA();
            log.error("Thread Interrupted," + Thread.currentThread().getName(), e);
            Thread.currentThread().interrupt();
        } finally {

            lock.unlock();
        }
        return new AsymmetricEntry<>(rsa.getPublicKeyBase64(), rsa.getPublicKeyBase64());
    }


    public static class AsymmetricEntry<K, V> {
        private final K pubKey;

        private final V privateKey;

        public AsymmetricEntry(K pubKey, V privateKey) {
            this.pubKey = pubKey;
            this.privateKey = privateKey;
        }

        public K getPubKey() {
            return pubKey;
        }

        public V getPrivateKey() {
            return privateKey;
        }
    }

    class Watchdog implements Runnable {

        @Override
        public void run() {
            lock.lock();
            try {
                // promise watchdog is active forever.
                while (true){
                    while (workQueue.isEmpty()) {
                        int count = 0;
                        for (; ; ) {
                            if (count++ >= maximumPoolSize) {
                                log.info("RSA池已补充完毕,请及时取用!workQueue:" + workQueue.size());
                                break;
                            }
                            workQueue.put(new RSA());
                        }
                    }

                    while (workQueue.size() >= maximumPoolSize) {
                        notEmpty.signal();
                        log.info("RSA池已经满了," + Thread.currentThread().getName() + "等待!");
                        notFull.await();
                    }
                }

            } catch (InterruptedException e) {
                log.error("Thread Interrupted," + Thread.currentThread().getName(), e);
                Thread.currentThread().interrupt();
            } finally {
                lock.unlock();
            }
        }
    }

}

/**
 * <h2>RSA全局签名校验</h2>
 * <pre>作用于方法之上,用来开启是否进行签名验证</pre>
 * <p>
 * 关联:{@link EnableSignatureVerify 启用签名校验}、
 * {@link SignatureIndex 签名参数}
 * </p>
 *
 **/
@Aspect
@Component
public class RsaSignatureVerifyAspect {

    @Resource
    private SignatureVerify signatureVerify;

    @Pointcut("@annotation(annotations.signature.EnableSignatureVerify)")
    public void aspect() {
        //
    }

    @Before("aspect()")
    public void before(JoinPoint point) throws BizException, ClassNotFoundException, IllegalAccessException {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Parameter[] parameters = signature.getMethod().getParameters();
        EnableSignatureVerify esv = signature.getMethod().getAnnotation(EnableSignatureVerify.class);
        String signStr = null;
        String orderCode = null;
        int index = 0;
        for (Parameter signatureParameter : parameters) {
            if (signatureParameter.isAnnotationPresent(SignatureIndex.class)) {
                if (SignatureIndex.SignatureMark.SIGNATURE.eq(signatureParameter.getAnnotation(SignatureIndex.class).value())) {
                    signStr = (String) point.getArgs()[index];
                } else if (SignatureIndex.SignatureMark.ORDER_CODE.eq(signatureParameter.getAnnotation(SignatureIndex.class).value())) {
                    orderCode = (String) point.getArgs()[index];
                }
            }
            index++;
        }

        if (isEmpty(orderCode) || isEmpty(signStr)) {
            EnumMap<SignatureIndex.SignatureMark, Object> waitSignParam = new EnumMap<>(SignatureIndex.SignatureMark.class);
            for (Object arg : point.getArgs()) {
                if (arg == null) {
                    continue;
                }

                generateSignParam(arg, waitSignParam, false);
                if (!waitSignParam.isEmpty()) {
                    break;
                }
            }

            if (waitSignParam.containsKey(SignatureIndex.SignatureMark.SIGNATURE))
                signStr = (String) waitSignParam.get(SignatureIndex.SignatureMark.SIGNATURE);

            if (waitSignParam.containsKey(SignatureIndex.SignatureMark.ORDER_CODE))
                orderCode = (String) waitSignParam.get(SignatureIndex.SignatureMark.ORDER_CODE);

        }

        // verify sign.
        if (isEmpty(signStr)) {
            log.warn("{} invoke,orderCode:{}, 签名为空!", signature.getMethod().getName(), orderCode);
            throw new BizException("签名不合法!");
        }

        // 针对不同的业务签名做验签(后续若验签业务多的话,可改为策略模式去做)
        if (EnableSignatureVerify.BizType.COMPANY_PAY != esv.business()) {
            // other? pass.
            return;
        }

        CompanyPaymentRequestDTO data = new CompanyPaymentRequestDTO();
        generateSignCommonData(data);
        data.setOrderCode(orderCode);
        if (Boolean.FALSE.equals(signatureVerify.verify(data, signStr, EnableSignatureVerify.BizType.COMPANY_PAY))) {
            log.warn("{} invoke,orderCode:{}, 签名验证失败!", signature.getMethod().getName(), orderCode);
            throw new BizException(ClientBizVerifyErrorCode.COMPANY_PAY_LOGIN_SIGNATURE_VERIFY_BAD);
        }

        log.info("{} invoke,orderCode:{}, 签名验证通过!", signature.getMethod().getName(), data.getOrderCode());
    }



    /**
     * 待签名的基本参数
     *
     * @param request 值传递
     */
    private void generateSignCommonData(CompanyPaymentRequestDTO request) {
        request.setVersion(CompanyPayConstant.VERSION);
        request.setServiceId(Constants.SERVICE);
        request.setSysFlag(SysFlagType.SYS_FLAG);
        request.setAlgorithm(RSA.getValue());
    }

    /**
     * 构建待签名的参数
     *
     * @param c            目标参数
     * @param signParamMap 待签名的数据
     * @param recursion 递归开关
     */
    private <C> void generateSignParam(C c, EnumMap<SignatureIndex.SignatureMark, Object> signParamMap, boolean recursion)
            throws ClassNotFoundException, IllegalAccessException {
        Class<?> clazz = Class.forName(c.getClass().getName());
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            executeGenerate(c, field, recursion)
                    .presentOrElseHandle(
                            () -> signParamMap,
                            (f, data) -> {
                                ReflectionUtils.makeAccessible(f);
                                try {
                                    if (f.getAnnotation(SignatureIndex.class) != null) {
                                        signParamMap.put(f.getAnnotation(SignatureIndex.class).value(), f.get(data));
                                    }
                                } catch (IllegalAccessException e) {
                                    log.error("generateSignParam reflect bad.", e);
                                }
                            });
        }
    }

    private static <C> boolean isBaseType(C c) {
        if (c instanceof Boolean) {
            return true;
        }
        if (c instanceof Integer) {
            return true;
        }
        if (c instanceof Long) {
            return true;
        }
        if (c instanceof Double) {
            return true;
        }
        if (c instanceof Byte) {
            return true;
        }
        if (c instanceof Float) {
            return true;
        }
        if (c instanceof Short) {
            return true;
        }
        if (c instanceof String) {
            return true;
        }

        if (c instanceof Character) {
            return true;
        }

        if (c instanceof Date) {
            return true;
        }
        if (c instanceof LocalDate) {
            return true;
        }

        return c instanceof LocalDateTime;
    }


    /**
     * 判断字符串是否为空
     *
     * @param str 目标
     * @return yes or no.
     */
    private static boolean isEmpty(String str) {
        return str == null || str.length() == 0;
    }

    /**
     * 函数式处理
     */
    @FunctionalInterface
    public interface AnnotationPresent {

        void presentOrElseHandle(Supplier<EnumMap<SignatureIndex.SignatureMark, Object>> noPresent, BiConsumer<? super Field, ? super Object> action) throws IllegalAccessException;

    }

    /**
     * 执行生成处理
     *
     * @param data 目标
     * @param field 当前目标字段
     * @param recursion 递归
     */
    private static <C> AnnotationPresent executeGenerate(C data, Field field, boolean recursion) {
        return (p, c) -> {
            if (!field.isAnnotationPresent(SignatureIndex.class)) {
                if (recursion) {
                    ReflectionUtils.makeAccessible(field);
                    Object val = field.get(data);
                    if (val != null && !isBaseType(val)) {
                        Field[] recursionFiled = val.getClass().getDeclaredFields();
                        for (Field f : recursionFiled) {
                            executeGenerate(val, f, true).presentOrElseHandle(p, c);
                        }
                    }
                }

            } else {
                c.accept(field, data);
            }
        };
    }
}


/**
 * 签名校验
 *
 **/
@Component
public class SignatureVerify {
    @Resource
    private RedisManager redisManager;

    /**
     * 验签
     *
     * @param waitSignatureData 参数
     * @param signature         签名
     * @return Boolean
     */
    public <T> Boolean verify(T waitSignatureData, String signature, EnableSignatureVerify.BizType bizType) throws ClassNotFoundException, IllegalAccessException {
        log.info("verify invoke start, waitSignatureData:{}, signature:{}", JSON.toJSONString(waitSignatureData), signature);
        String pubKey;

        if (EnableSignatureVerify.BizType.COMPANY_PAY == bizType) {
            EnumMap<SignatureIndex.SignatureMark, Object> waitSignParam = generateSignatureParams(waitSignatureData);
            String orderCode = null;
            if (waitSignParam.containsKey(SignatureIndex.SignatureMark.ORDER_CODE)) {
                orderCode = (String) waitSignParam.get(SignatureIndex.SignatureMark.ORDER_CODE);
            }
            pubKey = redisManager.getString(CompanyPayConstant.COMPANY_PAY_ASYMMETRIC_PUBLIC_KEY + orderCode);
            log.info("verify, pubKey:{}, orderCode:{}", pubKey != null, orderCode);
        } else {
            // 其他业务暂不处理
            return false;
        }

        if (StringUtils.isEmpty(pubKey)) {
            log.warn("verify, waitSignatureData:{} publicKey not find.", JSON.toJSONString(waitSignatureData));
            throw new BizException(ClientBizVerifyErrorCode.COMPANY_PAY_LOGIN_SIGNATURE_VERIFY_BAD);
        }

        // execute verify signature.
        return RSA.verifySignPublicKey(StrUtil.orderByAscii(JSON.toJSONString(waitSignatureData)), pubKey, signature);
    }

    private <T> EnumMap<SignatureIndex.SignatureMark, Object> generateSignatureParams(T data) throws ClassNotFoundException, IllegalAccessException {
        EnumMap<SignatureIndex.SignatureMark, Object> waitSignParam = new EnumMap<>(SignatureIndex.SignatureMark.class);
        Class<?> clazz = Class.forName(data.getClass().getName());
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            if (!field.isAnnotationPresent(SignatureIndex.class)) {
                continue;
            }
            ReflectionUtils.makeAccessible(field);
            Object val = field.get(data);
            if (field.getAnnotation(SignatureIndex.class) != null && val != null) {
                waitSignParam.put(field.getAnnotation(SignatureIndex.class).value(), val);
            }
        }

        return waitSignParam;
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
禁止转载,如需转载请通过简信或评论联系作者。
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,445评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,889评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,047评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,760评论 1 276
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,745评论 5 367
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,638评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,011评论 3 398
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,669评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,923评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,655评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,740评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,406评论 4 320
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,995评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,961评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,197评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,023评论 2 350
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,483评论 2 342

推荐阅读更多精彩内容