Deno nuggets: Get checksum of a file

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 checksum (SHA-1/256/384/512) of a file?

> cat ./testdata/sample.txt
Learning Deno Is Fun!
SHA-1 checksum is a79d516bcd53b94b401b064d4a953f55f9fc2aa3
SHA-512 checksum is fb71a03c94322ab66fb84acd75123c9911d95afc39c31df8340dcb6632cfde1c2bbae4b4c6da1c2fa9db8a7bd30fbf9c3cfac69b74159258976af9c278143e6f

Solution

Imports

The hex encode function from standard library’s encoding module is required to get the checksum as a hex string.

import {encode as he} from "https://deno.land/std/encoding/hex.ts";

Calculate checksum

There are three steps in calculating checksum of a file:

  • Read the contents of the file (Deno.readFile)
  • Calculate checksum (crypto.subtle.digest)
  • Convert checksum to hex string (hex encode)

Here is a function that computes checksum for a given algorithm and a file name:

import {encode as he} from "https://deno.land/std/encoding/hex.ts";const td=(d:Uint8Array)=>new TextDecoder().decode(d);async function getChecksum(algo:string, filename: string) { 
const d=await Deno.readFile(filename);
const c=await crypto.subtle.digest(algo, d);
return td(he(new Uint8Array(c)));
}

Here is the output from some sample runs:

await getChecksum('SHA-1', './testdata/sample.txt');
//a79d516bcd53b94b401b064d4a953f55f9fc2aa3
await getChecksum('SHA-512', './testdata/sample.txt');
//fb71a03c94322ab66fb84acd75123c9911d95afc39c31df8340dcb6632cfde1c2bbae4b4c6da1c2fa9db8a7bd30fbf9c3cfac69b74159258976af9c278143e6f
await getChecksum('SHA-1', './testdata/sample.pdf');
//7f09aec5f3a107b7ad129dc0d5e494666ef14b7a
await getChecksum('SHA-256', './testdata/sample.pdf');
//8b0fb7e275baab304265dc218d7deede1eb011055e2c569c6278965c0ca1c4b1

--

--