Intermediate
clideploy
Hashing
Hashing data is a common operation that is facilitated through Deno's support of the Web Crypto API. There are some more advanced uses that may require extensions to the api that are provided by the standard library.
Our original plaintext message
!--frsh-copybutton:1-->
const message = "The easiest, most secure JavaScript runtime.";
We first need to encode it into a uint8 array since web crypto only accepts them as arguments.
!--frsh-copybutton:2-->
const messageBuffer = new TextEncoder().encode(message);
We are now able to use the subtle crypto api to hash our original message. Unfortunately, this is a buffer so if we wanted to convert to a hex string we'd have a little more work to do.
!--frsh-copybutton:3-->
const hashBuffer = await crypto.subtle.digest("SHA-256", messageBuffer);
We can decode this into a string using the standard library's toHashString method
!--frsh-copybutton:4-->
import { toHashString } from "https://deno.land/std@0.175.0/crypto/to_hash_string.ts";
const hash = toHashString(hashBuffer);
console.log(hash);
The standard library also has some useful extensions to the Web Crypto API that is useful when doing something like hashing a file. These can be accessed through the drop "crypto" which is a drop in replacement for standard Web Crypto which differs to the native implementation when possible.
!--frsh-copybutton:5-->
import { crypto } from "https://deno.land/std@0.175.0/crypto/mod.ts";
Hashing a file is quite the common operation and doing this without loading the whole file into memory is a common requirement.
!--frsh-copybutton:6-->
const file = await Deno.open("example.txt", { read: true });
We can obtain an async iterable using the readable property
!--frsh-copybutton:7-->
const readableStream = file.readable;
We can then use this as an async iterable and hash the file
!--frsh-copybutton:8-->
const fileHashBuffer = await crypto.subtle.digest("SHA-256", readableStream);
We can then obtain the hex result using toHashString like earlier
!--frsh-copybutton:9-->
const fileHash = toHashString(fileHashBuffer);
console.log(fileHash);
Run this example locally using the Deno CLI:
deno run --allow-read https://byexample-wwv03xf36j0g.deno.dev/hashing.ts
Additional resources: