最近在研究数据库加密,看到了mycat-encrypt-server项目,看了一下代码,说是支持加密字段的模糊查询:
private void parserBinaryExpression(Expression expression, Set<String> columns, String tableAlias, String tableName) { BinaryExpression binartex = (BinaryExpression) expression; Expression leftExpression = binartex.getLeftExpression(); if (leftExpression instanceof Column) { Column column = (Column) leftExpression; String columnTable = column.getTable() == null ? null : column.getTable().getName().toLowerCase().replaceAll("`", ""); String columnName = column.getColumnName().toLowerCase().replaceAll("`", ""); if (columns.contains(columnName)) { if (isNotOwn(tableAlias, tableName, columnTable)) { return; } //如果是需要加密的列,获取右边 Expression rightExpression = binartex.getRightExpression(); if ((binartex instanceof EqualsTo || binartex instanceof NotEqualsTo) && rightExpression instanceof StringValue) { StringValue value = (StringValue) rightExpression; //如果是相等 if (StringUtils.isNotEmpty(value.getValue())) { value.setValue(EncryptHelper.hexWithPre(EncryptHelper.encode(value.getValue().getBytes(StandardCharsets.UTF_8)))); } } else if (binartex instanceof LikeExpression && rightExpression instanceof StringValue) { //如果是like StringValue stringValue = (StringValue) rightExpression; String strVal = stringValue.getValue(); String start = strVal.startsWith("%") ? "%" : EncryptHelper.PRE_ENCRYPT; String end = strVal.endsWith("%") ? "%" : ""; String value = strVal.replaceAll("^%+|%+$", ""); if (StringUtils.isNotEmpty(value)) { stringValue.setValue(start + EncryptHelper.hex(EncryptHelper.encode(value.getBytes(StandardCharsets.UTF_8))) + end); } } } } }