跳過到頁腳內容
NODE 說明

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

'your_salt_here' 替換為您用於自訂哈希輸出的唯一字串(鹽值)。

步驟 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 適用於 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 等敏感資料的實用方法。 透過使用哈希,您可以確保標識符的安全,同時在需要時保持檢索原始資料的能力。

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

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

Darrius Serrant
全棧軟件工程師 (WebOps)

Darrius Serrant 擁有邁阿密大學計算機科學學士學位,目前任職於 Iron Software 的全栈 WebOps 市場營銷工程師。從小就迷上編碼,他認為計算既神秘又可接近,是創意和解決問題的完美媒介。

在 Iron Software,Darrius 喜歡創造新事物,並簡化複雜概念以便於理解。作為我們的駐場開發者之一,他也自願教學生,分享他的專業知識給下一代。

對 Darrius 來說,工作令人滿意因為它被重視且有實際影響。

鋼鐵支援團隊

我們每週 5 天,每天 24 小時在線上。
聊天
電子郵件
打電話給我