/**
* <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;
}
}