跳至頁尾內容
節點幫助

Hashids NPM(開發者使用指南)

在現代網路應用中,確保資料安全和隱私至關重要。 保護資料庫 ID 或 URL 等敏感資訊的一種有效方法是使用Hashids ,這是一個 JavaScript 加密庫,可以將數位資料轉換為唯一、可逆和加密的雜湊值。 本文探討如何將 Hashids 無縫整合到 React 應用程式中,以混淆和解碼識別碼。

什麼是哈希德斯?

Hashids 是一個小巧而強大的函式庫,可以將數值資料轉換為雜湊字串。 主要目標是模糊數字標識符,以防止敏感資訊外洩。 這種轉換是可逆的,允許在需要時檢索原始數值資料。 Hashids 是一個 JavaScript 函式庫,可以從數字產生類似 YouTube 的 ID,對敏感資料進行編碼,或安全地向使用者公開資料庫 ID,或只是將 ID 與數字混淆。

將哈希表整合到你的 React 應用中

若要將 Hashids 整合到您的 React 應用程式中,請按照以下步驟操作:

步驟 1:安裝 Hashids npm

首先,在你的 React 專案中透過 npm 安裝 Hashids:

npm install hashids
# or
yarn add hashids
npm install hashids
# or
yarn add hashids
SHELL

步驟 2:初始化 Hashids 實例

在你的 React 元件或工具檔案中,使用鹽值(以及可選的最小哈希長度)初始化一個新的 Hashids 實例:

import { useState, useEffect } from 'react';
import Hashids from 'hashids';

// React component demonstrating Hashids integration
const MyComponent = () => {
  const [hashids, setHashids] = useState(null);

  useEffect(() => {
    // Initialize the Hashids library with a custom salt string and minimum hash length of 8
    const initHashids = new Hashids('your_salt_here', 8); // Replace 'your_salt_here' with your actual salt or configure custom alphabet
    setHashids(initHashids);
  }, []);

  // Other component logic here
  return (
    <div>
      {/* Your JSX content */}
    </div>
  );
};

export default MyComponent;
import { useState, useEffect } from 'react';
import Hashids from 'hashids';

// React component demonstrating Hashids integration
const MyComponent = () => {
  const [hashids, setHashids] = useState(null);

  useEffect(() => {
    // Initialize the Hashids library with a custom salt string and minimum hash length of 8
    const initHashids = new Hashids('your_salt_here', 8); // Replace 'your_salt_here' with your actual salt or configure custom alphabet
    setHashids(initHashids);
  }, []);

  // Other component logic here
  return (
    <div>
      {/* Your JSX content */}
    </div>
  );
};

export default MyComponent;
JAVASCRIPT

&#39;your_salt_here&#39;替換為您用於自訂雜湊輸出的唯一字串(鹽值)。

步驟 3:資料編碼和解碼

初始化完成後,您可以使用雜湊表對數字資料進行編碼和解碼。 例如,對資料庫 ID 進行編碼:

const encodedId = hashids.encode(12345); // Example: 'B0zGbvA9' non-sequential IDs
const encodedId = hashids.encode(12345); // Example: 'B0zGbvA9' non-sequential IDs
JAVASCRIPT

並將其解碼回原始 ID:

const decodedIds = hashids.decode('B0zGbvA9'); // Example: [12345]
const decodedIds = hashids.decode('B0zGbvA9'); // Example: [12345]
JAVASCRIPT

步驟 4:在元件中使用雜湊值

必要時,將哈希表整合到 React 元件中。 例如,將哈希 ID 作為 props 傳遞:

const MyComponent = ({ id }) => {
  // Encode ID using Hashids if the hashids instance is initialized
  const encodedId = hashids ? hashids.encode(id) : '';

  return (
    <div>
      <p>Encoded ID: {encodedId}</p>
      {/* Other JSX content */}
    </div>
  );
};
const MyComponent = ({ id }) => {
  // Encode ID using Hashids if the hashids instance is initialized
  const encodedId = hashids ? hashids.encode(id) : '';

  return (
    <div>
      <p>Encoded ID: {encodedId}</p>
      {/* Other JSX content */}
    </div>
  );
};
JAVASCRIPT

在 React 中使用哈希表的好處

-安全性:雜湊可以模糊數位 ID,防止直接對應到敏感訊息,從而增強資料隱私和安全性。 -易於整合:簡單的 npm 安裝和直接的 API 使 Hashids 易於在 React 應用程式中實現。 -靈活性:可自訂雜湊長度和鹽值,使雜湊值能夠靈活地適應應用程式的安全需求。

IronPDF簡介

IronPDF for Node.js是 Iron Software 出品的一款功能強大的 Node.js PDF 庫,它允許開發人員在其 .NET 專案中產生和編輯 PDF。 無論您需要從 HTML 建立 PDF、修改現有 PDF,或是將網頁轉換為 PDF 格式,IronPDF 都能滿足您的需求。

! Hashids NPM(開發者使用指南):圖 1 - IronPDF for Node.js:Node.js PDF 庫

主要特點

HTML 轉 PDF

輕鬆將HTML內容轉換為PDF文件。 此功能對於從網頁內容產生動態 PDF 特別有用。

URL 轉 PDF

直接從 URL 產生 PDF,讓您可以捕獲網頁內容並以程式設計方式將其儲存為 PDF 檔案。

PDF 處理

輕鬆合併、分割和操作現有 PDF 文件。 IronPDF 提供諸如追加頁面、分割文件等功能。

PDF 安全性

使用密碼加密或套用數位簽章來保護您的 PDF 文件。 IronPDF 提供多種選項,保護您的敏感文件免受未經授權的存取。

高品質輸出

產生高品質的 PDF 文檔,精確呈現文字、圖像和格式。 IronPDF 可確保您產生的 PDF 檔案與原始內容一致。

跨平台相容性

IronPDF與包括 Windows、Linux 和 macOS 在內的各種平台相容,使其適用於各種開發環境。

簡單集成

使用 IronPDF 的 npm 包,即可輕鬆整合到您的 Node.js 應用程式中。 該 API 文件齊全,可以輕鬆地將 PDF 生成功能整合到您的專案中。

安裝

若要安裝IronPDF NPM 包,請使用下列命令:

yarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64
yarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64
SHELL

使用 IronPDF 產生 PDF 文件並使用 HashIDs NPM 套件

安裝依賴項:首先,使用下列命令建立新的 Next.js 專案(如果尚未建立):請參閱此處

npx create-next-app@latest hashids-pdf --use-npm --example "https://github.com/vercel/next-learn/tree/main/basics/learn-starter"
npx create-next-app@latest hashids-pdf --use-npm --example "https://github.com/vercel/next-learn/tree/main/basics/learn-starter"
SHELL

接下來,導航到您的專案目錄:

cd hashids-pdf
cd hashids-pdf
SHELL

安裝所需軟體包:

yarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64
yarn add hashids
yarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64
yarn add hashids
SHELL

建立 PDF

現在,讓我們建立一個使用IronPDF產生 PDF 的簡單範例。 在您的 Next.js 元件(例如pages/index.tsx )中,加入以下程式碼:

PDF 產生 API:第一步是建立後端 API 來產生 PDF 文件。 由於 IronPDF 只能在伺服器端運行,我們需要建立一個 API,以便在使用者想要產生 PDF 時呼叫。 在pages/api/pdf.js路徑下建立文件,並新增以下內容。

IronPDF 需要許可證密鑰,您可以從許可證頁面取得並將其放入以下程式碼中。

// pages/api/pdf.js
import { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf";
import Hashids from 'hashids';

// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Your license key";

export default async function handler(req, res) {
  try {
    const initHashids = new Hashids('IronPDF Is Awesome and this is the salt', 8);
    const f = req.query.f;
    const l = initHashids.encode(f);

    let content = "<h1>Demo Hashids and Generate PDF Using IronPDF</h1>";
    content += "<p>Input:" + f + "</p>";
    content += "<p>HashID:" + l + "</p>";

    const pdf = await PdfDocument.fromHtml(content);
    const data = await pdf.saveAsBuffer();

    res.setHeader("Content-Type", "application/pdf");
    res.setHeader(
      "Content-Disposition",
      "attachment; filename=awesomeIron.pdf"
    );
    res.send(data);
  } catch (error) {
    console.error("Error generating PDF:", error);
    res.status(500).end();
  }
}
// pages/api/pdf.js
import { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf";
import Hashids from 'hashids';

// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Your license key";

export default async function handler(req, res) {
  try {
    const initHashids = new Hashids('IronPDF Is Awesome and this is the salt', 8);
    const f = req.query.f;
    const l = initHashids.encode(f);

    let content = "<h1>Demo Hashids and Generate PDF Using IronPDF</h1>";
    content += "<p>Input:" + f + "</p>";
    content += "<p>HashID:" + l + "</p>";

    const pdf = await PdfDocument.fromHtml(content);
    const data = await pdf.saveAsBuffer();

    res.setHeader("Content-Type", "application/pdf");
    res.setHeader(
      "Content-Disposition",
      "attachment; filename=awesomeIron.pdf"
    );
    res.send(data);
  } catch (error) {
    console.error("Error generating PDF:", error);
    res.status(500).end();
  }
}
JAVASCRIPT

現在修改index.js程式碼,如下所示,以使用 hashID 和 IronPDF。

import Head from "next/head";
import styles from "../styles/Home.module.css";
import React, { useState, useEffect } from "react";
import Hashids from 'hashids';

export default function Home() {
  const [text, setText] = useState("");
  const [etext, seteText] = useState("");
  const [hashids, setHashids] = useState(null);

  // Initialize Hashids on component mount
  useEffect(() => {
    const initHashids = new Hashids('IronPDF Is Awesome and this is the salt', 8);
    setHashids(initHashids);
  }, []);

  // Generate PDF by calling backend API
  const generatePdf = async () => {
    try {
      const response = await fetch("/api/pdf?f=" + text);
      const blob = await response.blob();
      const url = window.URL.createObjectURL(new Blob([blob]));
      const link = document.createElement("a");
      link.href = url;
      link.setAttribute("download", "awesomeIron.pdf");
      document.body.appendChild(link);
      link.click();
      link.parentNode.removeChild(link);
    } catch (error) {
      console.error("Error generating PDF:", error);
    }
  };  

  // Handle text change and encode input number
  const handleChange = (event) => {
    seteText(hashids ? hashids.encode(event.target.value) : '');
    setText(event.target.value);
  };

  return (
    <div className={styles.container}>
      <Head>
        <title>Generate PDF Using IronPDF</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <main>
        <h1>Demo Hashids and Generate PDF Using IronPDF</h1>
        <p>
          <span>Enter Url To get Hashids and Convert to PDF:</span>{" "}
        </p>
        <input type="number" value={text} onChange={handleChange} />
        <p>
          HashID of input: {etext}
        </p>        
        <button style={{ margin: 20, padding: 5 }} onClick={generatePdf}>
          Generate PDF 
        </button>
      </main>
      <style jsx>{`
        main {
          padding: 5rem 0;
          flex: 1;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
        }
        footer {
          width: 100%;
          height: 100px;
          border-top: 1px solid #eaeaea;
          display: flex;
          justify-content: center;
          align-items: center;
        }
        footer img {
          margin-left: 0.5rem;
        }
        footer a {
          display: flex;
          justify-content: center;
          align-items: center;
          text-decoration: none;
          color: inherit;
        }
        code {
          background: #fafafa;
          border-radius: 5px;
          padding: 0.75rem;
          font-size: 1.1rem;
          font-family:
            Menlo,
            Monaco,
            Lucida Console,
            Liberation Mono,
            DejaVu Sans Mono,
            Bitstream Vera Sans Mono,
            Courier New,
            monospace;
        }
      `}</style>
      <style jsx global>{`
        html,
        body {
          padding: 0;
          margin: 0;
          font-family:
            -apple-system,
            BlinkMacSystemFont,
            Segoe UI,
            Roboto,
            Oxygen,
            Ubuntu,
            Cantarell,
            Fira Sans,
            Droid Sans,
            Helvetica Neue,
            sans-serif;
        }
        * {
          box-sizing: border-box;
        }
      `}</style>
    </div>
  );
}
import Head from "next/head";
import styles from "../styles/Home.module.css";
import React, { useState, useEffect } from "react";
import Hashids from 'hashids';

export default function Home() {
  const [text, setText] = useState("");
  const [etext, seteText] = useState("");
  const [hashids, setHashids] = useState(null);

  // Initialize Hashids on component mount
  useEffect(() => {
    const initHashids = new Hashids('IronPDF Is Awesome and this is the salt', 8);
    setHashids(initHashids);
  }, []);

  // Generate PDF by calling backend API
  const generatePdf = async () => {
    try {
      const response = await fetch("/api/pdf?f=" + text);
      const blob = await response.blob();
      const url = window.URL.createObjectURL(new Blob([blob]));
      const link = document.createElement("a");
      link.href = url;
      link.setAttribute("download", "awesomeIron.pdf");
      document.body.appendChild(link);
      link.click();
      link.parentNode.removeChild(link);
    } catch (error) {
      console.error("Error generating PDF:", error);
    }
  };  

  // Handle text change and encode input number
  const handleChange = (event) => {
    seteText(hashids ? hashids.encode(event.target.value) : '');
    setText(event.target.value);
  };

  return (
    <div className={styles.container}>
      <Head>
        <title>Generate PDF Using IronPDF</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <main>
        <h1>Demo Hashids and Generate PDF Using IronPDF</h1>
        <p>
          <span>Enter Url To get Hashids and Convert to PDF:</span>{" "}
        </p>
        <input type="number" value={text} onChange={handleChange} />
        <p>
          HashID of input: {etext}
        </p>        
        <button style={{ margin: 20, padding: 5 }} onClick={generatePdf}>
          Generate PDF 
        </button>
      </main>
      <style jsx>{`
        main {
          padding: 5rem 0;
          flex: 1;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
        }
        footer {
          width: 100%;
          height: 100px;
          border-top: 1px solid #eaeaea;
          display: flex;
          justify-content: center;
          align-items: center;
        }
        footer img {
          margin-left: 0.5rem;
        }
        footer a {
          display: flex;
          justify-content: center;
          align-items: center;
          text-decoration: none;
          color: inherit;
        }
        code {
          background: #fafafa;
          border-radius: 5px;
          padding: 0.75rem;
          font-size: 1.1rem;
          font-family:
            Menlo,
            Monaco,
            Lucida Console,
            Liberation Mono,
            DejaVu Sans Mono,
            Bitstream Vera Sans Mono,
            Courier New,
            monospace;
        }
      `}</style>
      <style jsx global>{`
        html,
        body {
          padding: 0;
          margin: 0;
          font-family:
            -apple-system,
            BlinkMacSystemFont,
            Segoe UI,
            Roboto,
            Oxygen,
            Ubuntu,
            Cantarell,
            Fira Sans,
            Droid Sans,
            Helvetica Neue,
            sans-serif;
        }
        * {
          box-sizing: border-box;
        }
      `}</style>
    </div>
  );
}
JAVASCRIPT

程式碼解釋

  1. 使用者透過輸入文字方塊輸入數字。
  2. 輸入的數字使用 HashID 進行編碼並顯示。
  3. 當使用者點擊"產生 PDF"時,輸入的文字會被傳送到後端 API,該 API 會對文字進行編碼並產生 PDF 文件。

輸出

! Hashids NPM(開發者使用方法):圖 2

PDF

! Hashids NPM(開發者使用方法):圖 3

IronPDF 許可

IronPDF

請在此輸入許可證密鑰:

import { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf";
// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Add Your key here";
import { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf";
// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Add Your key here";
JAVASCRIPT

結論

將 Hashids 整合到 React 應用程式中是保護資料庫 ID 或 URL 等敏感資料的實用方法。 透過使用哈希,您可以確保標識符的安全,同時在需要時保持檢索原始資料的能力。

無論您是建立小型應用程式還是複雜的企業系統,Hashids 都能提供可靠的解決方案來增強 React 專案中的資料隱私和安全性,並且擅長將遞增的數字編碼為唯一的雜湊值。 雜湊表確保即使輸入數字中存在重複模式,也能產生不同的、不重複的雜湊值,從而維護應用程式中的資料完整性和安全性。

IronPDF是一款功能強大且用途廣泛的程式庫,對於希望在應用程式中提供全面的 PDF 生成、操作和管理功能的 node.js 開發人員來說,它脫穎而出。 無論您是建立 Web 應用程式、桌面軟體,還是將 PDF 功能整合到企業解決方案中。

柯蒂斯·週
技術撰稿人

Curtis Chau擁有卡爾頓大學電腦科學學士學位,專長於前端開發,精通Node.js、TypeScript、JavaScript和React。他熱衷於打造直覺美觀的使用者介面,喜歡使用現代框架,並擅長撰寫結構清晰、視覺效果出色的使用者手冊。

除了開發工作之外,柯蒂斯對物聯網 (IoT) 也抱有濃厚的興趣,致力於探索硬體和軟體整合的創新方法。閒暇時,他喜歡玩遊戲和製作 Discord 機器人,將他對科技的熱愛與創造力結合。