Deno nuggets: Calculate SHA

Mayank C
Tech Tonic

--

This article is a part of the Deno nuggets series, where each article attempts to suggest a pointed solution to a specific question that can be read in less than a minute. There is no ordering of nuggets.

Problem

How to calculate SHA of a string or bytes?

//string
I am learning Deno
//or, bytes
Uint8Array(18) [
73, 32, 97, 109, 32, 108,
101, 97, 114, 110, 105, 110,
103, 32, 68, 101, 110, 111
]
//SHA-1
Uint8Array(20) [
87, 21, 226, 100, 31, 13,
223, 84, 187, 156, 152, 154,
23, 99, 78, 138, 233, 188,
79, 227
]
//or, SHA-1 hex string
5715e2641f0ddf54bb9c989a17634e8ae9bc4fe3

Solution

Deno’s core runtime comes with a crypto module that provides a digest API that can be used to calculate SHA of any Uint8Array. It supports SHA-1, 256, 384, and 512. If the input is string, it needs to be converted to Uint8Array. The SHA output is returned in an ArrayBuffer that can be viewed using Uint8Array. If a hex string is required, the output bytes need to be converted using Array’s from, map and join functions.

Here is the complete code:

const is = "I am learning Deno";
const isb = new TextEncoder().encode(is);
const o = await crypto.subtle.digest("SHA-1", isb);
const ob = new Uint8Array(o);
const os = Array.from(ob).map((b) => b.toString(16).padStart(2, "0")).join("");

Here is the output of a run:

is: I am learning Deno ,
isb: Uint8Array(18) [
73, 32, 97, 109, 32, 108,
101, 97, 114, 110, 105, 110,
103, 32, 68, 101, 110, 111
] ,
o: ArrayBuffer {} ,
ob: Uint8Array(20) [
87, 21, 226, 100, 31, 13,
223, 84, 187, 156, 152, 154,
23, 99, 78, 138, 233, 188,
79, 227
] ,
os: 5715e2641f0ddf54bb9c989a17634e8ae9bc4fe3

Here is the output of the same run for SHA-512:

is: I am learning Deno ,
isb: Uint8Array(18) [
73, 32, 97, 109, 32, 108,
101, 97, 114, 110, 105, 110,
103, 32, 68, 101, 110, 111
] ,
o: ArrayBuffer {} ,
ob: Uint8Array(64) [
205, 46, 91, 230, 190, 149, 106, 129, 232, 155, 70,
6, 187, 135, 240, 33, 175, 206, 140, 48, 95, 240,
83, 126, 123, 245, 35, 166, 147, 165, 62, 7, 23,
205, 92, 105, 4, 165, 62, 175, 141, 18, 233, 221,
71, 38, 193, 157, 17, 83, 57, 222, 91, 72, 181,
217, 76, 203, 167, 77, 238, 131, 187, 82
] ,
os: cd2e5be6be956a81e89b4606bb87f021afce8c305ff0537e7bf523a693a53e0717cd5c6904a53eaf8d12e9dd4726c19d115339de5b48b5d94ccba74dee83bb52

--

--