How to create a hash with HmacSHA256 in deno?

Viewed 940

I know how to do that in Python.

#!/usr/bin/python
import sys
import os
import hashlib
import hmac
import base64

secretKey = bytes("passw@rd", 'UTF-8')
message = bytes(f'hello world\nhello deno', 'UTF-8')
encryptedKey = base64.b64encode(hmac.new(secretKey, message, digestmod=hashlib.sha256).digest())
print(encryptedKey)

code output

But I don't know how to do it in deno. I would like the same result of the python code above in deno.

1 Answers

You can create a HMAC-SHA256 hash with the help of the built-in crypto.subtle tools (available since mid of 2021) like shown below:

import { encode } from "https://deno.land/std/encoding/base64.ts"

const message = "hello world\nhello deno"

const encoder = new TextEncoder()
const keyBuf = encoder.encode("passw@rd");

const key = await crypto.subtle.importKey(
  "raw",
  keyBuf,
  {name: "HMAC", hash: "SHA-256"},
  true,
  ["sign", "verify"],
)

const data = encoder.encode(message);
const result = await crypto.subtle.sign("HMAC", key , data.buffer);
console.log(encode(new Uint8Array(result)));

kqfsOD/HMHBRL9F1Si4Y/qo9PCw2csuwXIGZK/P1IWc=


Prior to the introduction of crypto.subtle in Deno there were two choices based on external packages:

You can use God Crypto for it, but that requires an extra Base64 module. Important notice: the owner of God Crypto stopped maintaining the package, therefore it's not recommended to use anymore.

import { hmac } from "https://deno.land/x/god_crypto@v1.4.10/mod.ts"
import * as base64 from "https://deno.land/x/base64@v0.2.1/mod.ts"

let secretKey = "passw@rd"
let message = "hello world\nhello deno"

const result: string = base64.fromUint8Array(hmac("sha256", secretKey, message))

console.log(result)

kqfsOD/HMHBRL9F1Si4Y/qo9PCw2csuwXIGZK/P1IWc=

Or you can use the even more convinient hmac module, which has output encoding for "base64", "utf8" and "hex" integrated:

import { hmac } from "https://deno.land/x/hmac@v2.0.1/mod.ts";

let secretKey = "passw@rd"
let message = "hello world\nhello deno"

const result = hmac("sha256", secretKey , message , "utf8", "base64");
console.log(result)

kqfsOD/HMHBRL9F1Si4Y/qo9PCw2csuwXIGZK/P1IWc=

Related