LOGO OA教程 ERP教程 模切知識交流 PMS教程 CRM教程 開發文檔 其他文檔  
 
網站管理員

你是怎么實現數據庫加密數據的模糊查詢的

admin
2025年6月13日 20:18 本文熱度 114

做過金融項目或者政府項目的大佬肯定都實現過加密數據的模糊查詢功能,大家都是怎么實現的呢?今天就來簡單舉例一些實現加密數據模糊查詢的方案。
方案
查詢效率
開發成本
安全性
適用場景
應用層內存過濾
? 極差
? 低
? 高
極小數據量
數據庫函數解密
????
????
? 低
內部低安全需求
分詞+密文索引
????????
??????
? 高
大多數業務場景
同態加密
? 差
????????
? 高
學術研究/高安全
可信執行環境(TEE)
??????
????????
? 高
金融級安全

方案1:應用層內存過濾

原理

  1. 全表查詢加密數據

  2. 在內存中解密后過濾

// 偽代碼示例:危險!僅用于演示問題public List<UserunsafeSearch(String keyword) {    List<User> allUsers = userRepository.findAll(); // 查出全部數據    return allUsers.stream()            .filter(user -> decrypt(user.getName()).contains(keyword))            .collect(Collectors.toList());}

致命缺陷

  • 數據量大時內存溢出(OOM)

  • 全表掃描性能災難


方案2:數據庫函數解密

MySQL示例

-- 使用AES_DECRYPT函數(需數據庫存儲密鑰)SELECT * FROM users WHERE AES_DECRYPT(name_encrypted, 'secret_key'LIKE '%張%';

優缺點

  • ? 不改動業務代碼

  • ? 密鑰暴露在數據庫

  • ? 無法使用索引(全表掃描)

Java安全寫法

@Query(nativeQuery = true,       value = "SELECT * FROM users WHERE " +               "CONVERT(AES_DECRYPT(name_encrypted, ?1) USING utf8) LIKE ?2")List<UsersearchByName(String key, String keyword);


方案3:分詞+密文索引(推薦)

1. 核心思路

  • 存儲階段
    將原始數據(如"張三豐")拆分為分詞("張"、"三"、"豐"、"張三"、"三豐"),每個分詞加密后單獨存儲。

  • 查詢階段
    用戶輸入"張"時,先加密"張"得到密文,再用密文去分詞索引表查詢。

2. 代碼實現

(1). 增強版分詞策略

// 引入中文分詞器(需添加依賴)<dependency>    <groupId>com.janeluo</groupId>    <artifactId>ikanalyzer</artifactId>    <version>2012_u6</version></dependency>
public class EnhancedTokenizer {    public static List<StringsmartTokenize(String text) {        List<String> tokens = new ArrayList<>();        try (StringReader reader = new StringReader(text)) {            IKSegmenter seg = new IKSegmenter(reader, true);            Lexeme lex;            while ((lex = seg.next()) != null) {                tokens.add(lex.getLexemeText());                // 增加組合分詞(如"張三豐"生成"張"、"三"、"豐"、"張三"、"三豐")                if (lex.getLength() > 1) {                    for (int i = 2; i <= lex.getLength(); i++) {                        tokens.add(text.substring(lex.getBeginPosition(),                                 lex.getBeginPosition() + i));                    }                }            }        }        return tokens.stream().distinct().collect(Collectors.toList());    }}

2. 雙重加密索引表

// 索引表結構建議@Entity@Table(name = "user_search_index")public class SearchIndex {    @Id    @GeneratedValue    private Long id;
    @Column(name = "user_id")    private Long userId;
    @Column(name = "token_hash")  // 用于快速匹配    private String tokenHash;
    @Column(name = "token_cipher") // 用于精確驗證    private String tokenCipher;
    // 使用不同密鑰加密    public static SearchIndex create(Long userId, String token) throws Exception {        SearchIndex index = new SearchIndex();        index.setUserId(userId);        index.setTokenHash(AESUtil.encryptWithKey(token, "HASH_KEY"));        index.setTokenCipher(AESUtil.encryptWithKey(token, "CIPHER_KEY"));        return index;    }}

3. 智能查詢流程

public List<UsersecureFuzzySearch(String keyword) throws Exception {    // 1. 生成候選分詞    List<String> tokens = EnhancedTokenizer.smartTokenize(keyword);
    // 2. 并行加密提高性能    List<String> hashList = tokens.parallelStream()            .map(t -> {                try {                    return AESUtil.encryptWithKey(t, "HASH_KEY");                } catch (Exception e) {                    throw new RuntimeException(e);                }            })            .collect(Collectors.toList());
    // 3. 分頁查詢避免內存壓力    Pageable page = PageRequest.of(0100);    List<Long> userIds = indexRepository            .findUserIdsByTokenHashes(hashList, page);
    // 4. 二次驗證(防止哈希碰撞)    return userRepository.findAllById(userIds).stream()            .filter(user -> {                try {                    String decrypted = AESUtil.decrypt(user.getNameCipher());                    return decrypted.contains(keyword);                } catch (Exception e) {                    return false;                }            })            .collect(Collectors.toList());}


方案4:同態加密(學術級方案)

基于SEAL庫的實現

// 添加依賴(微軟SEAL庫Java版)<dependency>    <groupId>com.microsoft.seal</groupId>    <artifactId>seal-jni</artifactId>    <version>3.7.2</version></dependency>
public class HomomorphicSearch {    public static void demo() throws Exception {        // 1. 初始化加密上下文        EncryptionParameters params = new EncryptionParameters(SchemeType.bfv);        params.setPolyModulusDegree(4096);        params.setCoeffModulus(CoeffModulus.BFVDefault(4096));        params.setPlainModulus(PlainModulus.Batching(409620));
        SEALContext context = new SEALContext(params);
        // 2. 生成密鑰        KeyGenerator keyGen = new KeyGenerator(context);        PublicKey publicKey = keyGen.createPublicKey();        SecretKey secretKey = keyGen.secretKey();
        // 3. 加密數據        Encryptor encryptor = new Encryptor(context, publicKey);        Plaintext plain = new Plaintext("123"); // 要加密的數字        Ciphertext encrypted = new Ciphertext();        encryptor.encrypt(plain, encrypted);
        // 4. 在密文上計算(此處演示加法)        Evaluator evaluator = new Evaluator(context);        Ciphertext result = new Ciphertext();        evaluator.add(encrypted, encrypted, result); // 密文+密文
        // 5. 解密驗證        Decryptor decryptor = new Decryptor(context, secretKey);        Plaintext decrypted = new Plaintext();        decryptor.decrypt(result, decrypted);        System.out.println(decrypted); // 應輸出246    }}

現實限制

  • 僅支持有限運算(加減/乘)

  • 性能差(單次操作需100ms+)

  • 不支持字符串操作


方案5:可信執行環境(TEE)

基于Intel SGX的解決方案

// SGX加密區(enclave)內代碼示例void ecall_fuzzy_search(const char* encrypted_query, size_t len) {    // 1. 解密查詢條件    std::string query = decrypt_in_enclave(encrypted_query, len);
    // 2. 直接查詢數據庫(enclave內可見明文)    sqlite3* db;    sqlite3_open(":memory:", &db);    std::string sql = "SELECT * FROM users WHERE name LIKE '%" + query + "%'";
    // 3. 加密結果返回    encrypt_results(db_exec(sql));}

優勢

  • 硬件級安全

  • 性能接近明文查詢
    挑戰

  • 需要特定硬件支持

  • 開發復雜度高


閱讀原文:原文鏈接


該文章在 2025/6/14 16:36:35 編輯過
關鍵字查詢
相關文章
正在查詢...
點晴ERP是一款針對中小制造業的專業生產管理軟件系統,系統成熟度和易用性得到了國內大量中小企業的青睞。
點晴PMS碼頭管理系統主要針對港口碼頭集裝箱與散貨日常運作、調度、堆場、車隊、財務費用、相關報表等業務管理,結合碼頭的業務特點,圍繞調度、堆場作業而開發的。集技術的先進性、管理的有效性于一體,是物流碼頭及其他港口類企業的高效ERP管理信息系統。
點晴WMS倉儲管理系統提供了貨物產品管理,銷售管理,采購管理,倉儲管理,倉庫管理,保質期管理,貨位管理,庫位管理,生產管理,WMS管理系統,標簽打印,條形碼,二維碼管理,批號管理軟件。
點晴免費OA是一款軟件和通用服務都免費,不限功能、不限時間、不限用戶的免費OA協同辦公管理系統。
Copyright 2010-2025 ClickSun All Rights Reserved

黄频国产免费高清视频,久久不卡精品中文字幕一区,激情五月天AV电影在线观看,欧美国产韩国日本一区二区
欧美十八禁激情在线观看视频 | 亚洲国产精品第一区 | 在线精品亚洲观看不卡欧 | 在线亚洲综合亚洲网色就色 | 午夜欧美成是人在线观看 | 日本午夜一区二区三区影院 |