deno.com

雜湊 (Hashing)

在 Github 上編輯 (Edit on Github)

雜湊資料是一種常見的操作,透過 Deno 對 Web Crypto API 的支援得以實現。此外,Deno 標準函式庫的實作擴展了標準 API,允許更進階的使用。(Hashing data is a common operation that is facilitated through Deno's support for the Web Crypto API. In addition, the Deno Standard Library's implementation extends the standard API, allowing for more advanced uses.)

在我們的第一個範例中,我們將雜湊字串變數的內容。(In our first example, we'll hash the contents of a string variable.)
const message = "The easiest, most secure JavaScript runtime.";
在我們可以將訊息傳遞給雜湊函數之前,我們首先需要將其編碼為 uint8 陣列。(Before we can pass our message to the hashing function, we first need to encode it into a uint8 array.)
const messageBuffer = new TextEncoder().encode(message);
在這裡,我們使用內建的 crypto.subtle.digest 方法來雜湊我們的原始訊息。雜湊值會以 ArrayBuffer 的形式傳回。為了取得字串,我們需要做更多的工作。(Here, we use the built-in crypto.subtle.digest method to hash our original message. The hash is returned as an ArrayBuffer. To obtain a string we'll need to do a little more work.)
const hashBuffer = await crypto.subtle.digest("SHA-256", messageBuffer);
我們可以透過標準函式庫的 encodeHex 方法將其解碼為字串。(We can decode this into a string using the standard library's encodeHex method.)
import { encodeHex } from "jsr:@std/encoding/hex";
const hash = encodeHex(hashBuffer);
console.log(hash);
在我們的第二個範例中,我們將雜湊檔案的內容。雜湊檔案是一種常見的操作,在不將整個檔案載入記憶體的情況下執行此操作是一種典型的需求。(For our second example, we'll hash the contents of a file. Hashing a file is a common operation and doing this without loading the whole file into memory is a typical requirement.)
標準函式庫對 Web Crypto API 進行了擴展,這些擴展在執行檔案雜湊等操作時非常有用。這些擴展可以透過 "crypto" 模組存取,它是 Web Crypto API 的直接替換,在可能的情況下會委派給原生實作。(The standard library has extensions to the Web Crypto API that are useful when doing things like hashing a file. These can be accessed through the "crypto" module, a drop-in replacement for the Web Crypto API that delegates to the native implementation when possible.)
import { crypto } from "jsr:@std/crypto";
const file = await Deno.open("example.txt", { read: true });
我們使用 readable 屬性取得一個非同步可迭代物件。(We obtain an async iterable using the readable property.)
const readableStream = file.readable;
這次,當我們呼叫 crypto.subtle.digest 時,我們使用的是匯入的版本,它允許我們對非同步可迭代物件進行操作。(This time, when we call crypto.subtle.digest, we're using the imported version that allows us to operate on the async iterable.)
const fileHashBuffer = await crypto.subtle.digest("SHA-256", readableStream);
最後,我們像之前一樣使用 encodeHex 取得十六進制結果。(Finally, we obtain the hex result using encodeHex like earlier.)
const fileHash = encodeHex(fileHashBuffer);
console.log(fileHash);

使用 Deno CLI 在本機執行此範例 (this example) (Run this example locally using the Deno CLI)

deno run --allow-read https://deno-docs.dev.org.tw/examples/scripts/hashing.ts

您找到需要的資訊了嗎? (Did you find what you needed?)

隱私權政策 (Privacy policy)