1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
| import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.ke.zhaopin.manage.server.config.mybatis.interceptor.anno.Decrypted; import com.lianjia.ctt.kinko.spi.CipherSpi; import com.sun.istack.internal.NotNull; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.apache.ibatis.binding.MapperMethod; import org.apache.ibatis.executor.parameter.ParameterHandler; import org.apache.ibatis.plugin.*; import org.apache.ibatis.reflection.MetaObject; import org.apache.ibatis.scripting.defaults.DefaultParameterHandler; import org.apache.ibatis.session.Configuration; import org.apache.ibatis.session.defaults.DefaultSqlSession; import org.joor.Reflect; import reactor.core.publisher.Flux;
import java.lang.reflect.Array; import java.lang.reflect.Field; import java.sql.PreparedStatement; import java.util.*; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.function.Function; import java.util.stream.Collectors;
@Intercepts({ @Signature(type = ParameterHandler.class, method = "setParameters", args = {PreparedStatement.class}), }) @Slf4j public class EncryptInterceptor implements Interceptor {
private static final String COLLECTION_KEY = "collection"; private static final String ARRAY_KEY = "array";
private final LoadingCache<Class, List<String>> decryptFieldCaches = CacheBuilder.newBuilder() .maximumSize(200) .expireAfterAccess(10L, TimeUnit.MINUTES) .build(new CacheLoader<Class, List<String>>() { @Override public List<String> load(Class key) { return Arrays.stream(key.getDeclaredFields()) .filter(f -> f.getAnnotation(Decrypted.class) != null) .filter(f -> { boolean isString = f.getType() == String.class; if (!isString) { log.warn(f.getName() + "is not String, actual type is " + f.getType().getSimpleName() + " ignored"); } return isString; }) .map(Field::getName) .collect(Collectors.toList()); } } );
private CipherSpi cipherSpi;
public EncryptInterceptor(CipherSpi cipherSpi) { this.cipherSpi = cipherSpi; }
@Override public Object intercept(Invocation invocation) throws Throwable {
Flux<CryptContext> contextFlux = Flux.empty();
do { if (!(invocation.getTarget() instanceof DefaultParameterHandler)) break;
final Reflect parameterHandler = Reflect.on(invocation.getTarget()); final Object parameterObject = parameterHandler.get("parameterObject"); final Configuration configuration = parameterHandler.get("configuration");
if (parameterObject instanceof DefaultSqlSession.StrictMap) { DefaultSqlSession.StrictMap<?> paramMap = (DefaultSqlSession.StrictMap<?>) parameterObject;
Collection<?> collection = null; Class<?> componentType = null; if (paramMap.containsKey(COLLECTION_KEY)) { collection = (Collection<?>) paramMap.get(COLLECTION_KEY); componentType = collection.iterator().next().getClass(); } else if (paramMap.containsKey(ARRAY_KEY)) { Object[] array = (Object[]) paramMap.get(ARRAY_KEY); componentType = array.getClass().getComponentType(); collection = Arrays.asList(array); }
if (!isUserDefinedClass(componentType)) break;
contextFlux = collection(configuration, collection, componentType);
} else if (parameterObject instanceof MapperMethod.ParamMap) { MapperMethod.ParamMap<?> paramMap = (MapperMethod.ParamMap<?>) parameterObject;
final List<?> params = paramMap.values().stream().filter(Objects::nonNull).distinct().collect(Collectors.toList());
for (Object parameter : params) { if (parameter instanceof Collection) { Collection<?> collection = (Collection<?>) parameter; if (collection.isEmpty()) { continue; }
Class<?> componentType = collection.iterator().next().getClass(); if (!isUserDefinedClass(componentType)) { continue; } final Flux<CryptContext> collectionFlux = collection(configuration, collection, componentType); contextFlux = contextFlux.concatWith(collectionFlux);
} else if (parameter.getClass().isArray()) { if (Array.getLength(parameter) == 0) continue; final Class<?> componentType = parameter.getClass().getComponentType(); if (!isUserDefinedClass(componentType)) { continue; } Collection<?> collection = Arrays.asList((Object[]) parameter);
final Flux<CryptContext> collectionFlux = collection(configuration, collection, componentType); contextFlux = contextFlux.concatWith(collectionFlux);
} else if (isUserDefinedClass(parameter.getClass())) { final Flux<CryptContext> singleFlux = collection(configuration, Collections.singletonList(parameter), parameter.getClass()); contextFlux = contextFlux.concatWith(singleFlux); } }
} else if (isUserDefinedClass(parameterObject.getClass())) { contextFlux = collection(configuration, Collections.singletonList(parameterObject), parameterObject.getClass()); } else { }
} while (false);
final List<CryptContext> cryptContexts = encrypt(contextFlux);
invocation.proceed();
restore(cryptContexts);
return null; }
private void restore(List<CryptContext> cryptContexts) { for (CryptContext cryptContext : cryptContexts) { cryptContext.metaObject.setValue(cryptContext.fieldName, cryptContext.value); } }
private Flux<CryptContext> collection(Configuration configuration, Collection<?> collection, Class<?> componentType) throws ExecutionException { final List<String> fieldNames = this.getDecryptFields(componentType);
return Flux.fromIterable(collection) .map(configuration::newMetaObject) .flatMapIterable(metaObject -> fieldNames.stream().map(fieldName -> new CryptContext(metaObject, fieldName)).collect(Collectors.toList())); }
private List<CryptContext> encrypt(Flux<CryptContext> contextFlux) { return contextFlux .filter(context -> StringUtils.isNotBlank(context.value)) .buffer(1000) .doOnNext(contexts -> { Map<String, String> secretMap = Collections.emptyMap(); try { secretMap = cipherSpi.batchEncrypt(contexts.stream().map(CryptContext::getValue).distinct().collect(Collectors.toList())); } catch (Exception e) {
} for (CryptContext context : contexts) { context.secret = secretMap.get(context.value); } }) .flatMapIterable(Function.identity()) .doOnNext(context -> context.metaObject.setValue(context.fieldName, context.secret)) .collectList() .block(); }
@NotNull private List<String> getDecryptFields(Class<?> modelClazz) throws ExecutionException { return this.decryptFieldCaches.get(modelClazz); }
private boolean isUserDefinedClass(Class<?> clazz) { return !clazz.isPrimitive() && !clazz.getPackage().getName().startsWith("java"); }
@Override public Object plugin(Object target) { return Plugin.wrap(target, this); }
@Override public void setProperties(Properties properties) {
} }
@Getter class CryptContext {
CryptContext(MetaObject metaObject, String fieldName) { this.metaObject = metaObject; this.fieldName = fieldName; this.value = (String) metaObject.getValue(fieldName); if (StringUtils.isBlank(value)) { this.secret = StringUtils.EMPTY; } }
final MetaObject metaObject;
final String fieldName;
final String value;
String secret; }
|