You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在TypeORM中查询匹配Argon哈希列的数据库记录?

在TypeORM中实现Argon哈希匹配查询

方案一:应用层验证(通用所有数据库)

大部分数据库原生不支持Argon验证函数,小数据量场景下可以先拉取全表数据,再在应用层用Argon库验证:

  1. 安装并引入argon2库
  2. 编写查询逻辑:
import { getRepository } from "typeorm";
import argon2 from "argon2";
import { YourEntity } from "./entities/YourEntity";

async function findMatchingRecord(inputValue: string) {
  const repo = getRepository(YourEntity);
  const allRecords = await repo.find();

  for (const record of allRecords) {
    try {
      if (await argon2.verify(record.rt, inputValue)) {
        return record;
      }
    } catch (err) {
      console.error("Argon验证出错:", err);
    }
  }
  return null;
}

⚠️ 注意:数据量大时全表查询性能极差,仅适合小数据集。

方案二:数据库层面验证(仅支持带Argon扩展的数据库)

如果你的数据库支持Argon扩展(比如PostgreSQL的argon2扩展),可以直接在数据库层面完成验证,避免全表数据传输:

PostgreSQL示例:

  1. 先在数据库中安装扩展:
CREATE EXTENSION IF NOT EXISTS argon2;
  1. 使用TypeORM QueryBuilder查询:
import { getRepository } from "typeorm";
import { YourEntity } from "./entities/YourEntity";

async function findMatchingRecord(inputValue: string) {
  return getRepository(YourEntity)
    .createQueryBuilder("t")
    .where("argon2_verify(:input, t.rt)", { input: inputValue })
    .getOne();
}

或者用原生SQL:

import { getConnection } from "typeorm";

async function findMatchingRecord(inputValue: string) {
  const result = await getConnection().query(
    "SELECT * FROM your_table WHERE argon2_verify($1, rt)",
    [inputValue]
  );
  return result[0] || null;
}

⚠️ 注意:不同数据库的Argon验证函数名称可能不同,需根据实际使用的扩展调整函数名。

关键提示

  • 数据量大时优先用数据库层面验证,能大幅减少应用层与数据库间的数据传输。
  • 确保应用层使用的Argon库版本和数据库扩展版本兼容,避免验证不通过。

内容的提问来源于stack exchange,提问作者Majva

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 03:34:51