import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.HashMap;
/**
* 加密后实现模糊查询,支持最少N位组成的字符串通过AES\MD5\BASE64等加密方式
* @author Bobo
* @description
* @date 2024/5/11 9:18
*/
public class ExampleOfEncryptedFuzzyQuery {
public static void main(String[] args) throws UnsupportedEncodingException {
String phoneNumber = "13812345678";
String encrypt = ExampleOfEncryptedFuzzyQuery.encrypt(phoneNumber);
//模拟数据库
HashMap<String, String> map = new HashMap<>();
map.put(encrypt, phoneNumber);
System.out.println("map中,key:" + encrypt + ",value:" + phoneNumber);
//模糊查询
String fuzzyQuery = "138123";
String fuzzyQueryEncrypt = ExampleOfEncryptedFuzzyQuery.encrypt(fuzzyQuery);
String key = map.keySet().stream().filter(x -> x.contains(fuzzyQueryEncrypt)).findAny().orElse(null);
if (fuzzyQueryEncrypt == null || !map.containsKey(key)) {
System.out.println("没有查询到");
}
System.out.println("入参:" + fuzzyQueryEncrypt + ",查询结果:" + map.get(key));
}
/**
* @param phoneNumber
* @return
* @throws UnsupportedEncodingException
*/
public static String encrypt(String phoneNumber) throws UnsupportedEncodingException {
if (phoneNumber.length() < 4) {
throw new RuntimeException("模糊查询最小长度为4");
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < phoneNumber.length() - 3; i++) {
//截取前四位,加密后添加到sb中
String value = phoneNumber.substring(i, i + 4);
String encryptValue = Base64.getEncoder().encodeToString(value.getBytes("utf-8"));
System.out.println("加密前:" + value + ",加密后:" + encryptValue);
sb.append(encryptValue);
}
return sb.toString();
}
}
加密前:1381,加密后:MTM4MQ==
加密前:3812,加密后:MzgxMg==
加密前:8123,加密后:ODEyMw==
加密前:1234,加密后:MTIzNA==
加密前:2345,加密后:MjM0NQ==
加密前:3456,加密后:MzQ1Ng==
加密前:4567,加密后:NDU2Nw==
加密前:5678,加密后:NTY3OA==
map中,key:MTM4MQMzgxMgODEyMwMTIzNAMjM0NQMzQ1NgNDU2NwNTY3OA,value:13812345678
加密前:1381,加密后:MTM4MQ==
加密前:3812,加密后:MzgxMg==
加密前:8123,加密后:ODEyMw==
入参:MTM4MQMzgxMgODEyMw==,查询结果:13812345678