加密后实现模糊查询


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

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值