Hướng dẫn what is hmac javascript?

[TL;DR] I will easily introduce MAC and HMAC concepts and provide very simple JavaScript sample code that you will be even able to use in your browser console.

Hướng dẫn what is hmac javascript?

MAC stands for Message Authentication Code, and it also known as tag, and in communications sometimes is substituted by MIC or message integrity code.

What is a MAC for?

From a general point of view, a MAC is a piece of information that protects a message by:

  • verifying data integrity, i.e. that the message has not been tampered.
  • verifying its authenticity, confirming that it comes from the stated sender.

This is specially important when the message has to travel through unsecured channels. Specific use cases will be listed below.

How does MAC work?

  1. The sender A wants to send a message M to a receiver B.
  2. The sender A and the receiver B sharea key K.
  3. The sender uses a signing algorithm S to calculate a tag T given the shared key K and the message M.
  4. The receiver B uses a verifying algorithm V to verify the authenticity of the message M given the key K and the tag T. That is, the algorithm returns accepted if neither the tag T nor the message M have been tampered with. Otherwise, it returns rejected.

Requisites for a secure message authentication code

It must resist an adversary’s attempt to forge tags for arbitrary, selected or all messages, including under conditions of known- or chosen-message. That is, it must resist the forgery of digital signature.

It should be computationally infeasible to compute a valid tag of the given message without knowledge of the key.

HMAC

HMAC (hash-based message authentication code) is a particular type of message authentication code (MAC). As with any MAC, the hash function can be used for both verifying data integrity and authentication of the message.

The hash function name is used to term the different MAC functions with the pattern HMAC-X, for example HMAC-SHA256 or HMAC-SHA3–512.

JavaScript example

Open your browser dev tools to try the following snippets on the console. These snippets should work also with Node.js.

This function implements the HMAC-SHA256 version:

async function hmacSha256Hex(secret, message) {
const enc = new TextEncoder("utf-8");
const algorithm = { name: "HMAC", hash: "SHA-256" };
const key = await crypto.subtle.importKey(
"raw",
enc.encode(secret),
algorithm,
false, ["sign", "verify"]
);
const hashBuffer = await crypto.subtle.sign(
algorithm.name,
key,
enc.encode(message)
);
const hashArray = Array.from(new Uint8Array(hashBuffer)); const hashHex = hashArray.map(
b => b.toString(16).padStart(2, '0')
).join('');
return hashHex;
}

Using this function is as simple as the following:

await hmacSha256Hex(
"key",
"The quick brown fox jumps over the lazy dog"
);
//f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8

In the previous example, mapping to the MAC explanation, we have that key K has the value “key”, the message M has the value “The quick brown fox jumps over the lazy dog” and the tag T has the value “f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8”.

Usage scenarios for HMAC

So by now, you should understand how HMAC works — if not, please tell me in the comments which is the obscure part so I can improve it. You may wonder which are particular scenarios for this technology. Well, here are a few of them that will help you when you face different challenges:

  • Password reset link. You can send an e-mail with a reset link that is only valid for a certain time. With HMAC, you can do this without additional server states.
  • Links in verifying email addresses in order to create or activate accounts.
  • Authenticating data sent by external applications.
  • Authenticating form data that has been sent to the user browser and the posted back.
  • For internet of things (IoT) due to its low computational cost, in particular for Low-Power Wide-Area Networks.
  • HMAC based authentication (for instance, is the main authentication used by Amazon Web Services for request authentication).
  • As a data pseudonymisation technique, for example to comply with GDPR. This is, by the way, recommended by the European Union Agency for Cybersecurity (ENISA).

I want to compute the SHA256 based HMAC for some key and a message in front-end using JavaScript. It's easily done in Python like so:

import hmac
h = hmac.new(b'key', b'message', 'sha256')
print(h.hexdigest())

I searched and found something in NodeJS but can't do the same thing in front-end (I mean in browser of the user), which I guess I need to bundle the required library and do the stuff but could not figure out how.

asked Oct 17, 2019 at 20:41

4

npm i js-sha256 [link]

will install it on the domain of your choice, in node_modules/ and you can link it from there.

console.log(sha256.hmac('key', 'message'));

answered Oct 17, 2019 at 20:53

taotao

72.4k13 gold badges104 silver badges130 bronze badges

3

Not the answer you're looking for? Browse other questions tagged javascript hash frontend sha256 hmac or ask your own question.

Regular expression kiểm tra gmail c

Home Java Xác thực Email trong Java với regular expressions October 22, 2021 Mục lục1 Xác thực email trong Java2 Xác thực email với Regular Expression3 Xác thực email nâng cao ...

Hướng dẫn get function name javascript

Does anyone know if there is a way to get JavaScript function name. For example I got a function like function test1(){ alert(1); } I have it in my head section. Then I create an object obj1 and put ...

Hướng dẫn dùng schooloop JavaScript

Lập trình hàm (Functional programming) không còn là cái tên lạ lẫm trong thời gian gần đây, nhiều lập trình viên đã và đang dần chuyển đổi theo mô hình lập ...

Hướng dẫn tính toán trong javascript

Cơ bản về các biểu thức và toán tử trong Javascript, các toán tử js cần nắm vững ở đây là các toán tử số học, toán tử gán, toán tử so sánh, toán tử ...

Hướng dẫn dùng text reverse python

Nội dung chínhĐảo ngược list ban đầu trong python| Phương thức reverse()Đảo ngược list và tạo ra một list mới trong python | Cắt (slice) listĐảo ngược list và ...

Hướng dẫn dùng ouput JavaScript

Khả năng hiển thị của JavaScriptJavaScript có thể hiện thị dữ liệu bằng một số cách khác nhau:Viết vào trong một thành phần HTML dùng innerHTML.Viết vào ...

Hướng dẫn format price php

(PHP 4 >= 4.3.0, PHP 5, PHP 7)money_format — Formats a number as a currency stringWarningThis function has been DEPRECATED as of PHP 7.4.0, and REMOVED as of PHP 8.0.0. Relying on this function ...

Hướng dẫn dùng i.t.e.r. python

Chào cả nhà 🥳! Chào BeautyOnCode 🤣Just for vui tí, thực ra đó là cách gia đình mình chào nhau dạo gần đây lolBa bảo: “Chào Minh Hoàng!”. Chicken bảo: “Chào Ba ...

Hướng dẫn dùng sha256 length trong PHP

Như Johannes Gorset đã chỉ ra, bài đăng của Thomas Ptacek từ Matasano Security giải thích tại sao các hàm băm đơn giản, đa năng như MD5, SHA1, SHA256 và SHA512 là những ...

Hướng dẫn dùng objeto JavaScript

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.Try itSyntaxconst [a, b] = ...

Hướng dẫn new date() javascript

Đã đăng vào thg 6 19, 2020 10:01 SA 4 phút đọc Hàm xử lý ngày tháng (Date) trong JavascriptBài trước chúng ta đã tìm hiểu đối tượng Date trong Javascript rồi thì ...

Hướng dẫn array assign javascript

DescriptionIn JavaScript, arrays arent primitives but are instead Array objects with the following core characteristics:JavaScript arrays are resizable and can contain a mix of different data types. ...

Hướng dẫn dùng d.o.m.s. JavaScript

Javascript là một ngôn ngữ được sử dụng trong các trình duyệt Browser nên nó đóng một vai trò khá quan trọng trong các ứng dụng website. Và nhiệm vụ của ...

Hướng dẫn php next

Trang chủ Phát triển web PHP Hàm next() trong PHPHướng dẫn cách sử dụng hàm next() về mảng trong lập trình PHPNội dung chínhTác dụng của hàm next()More ExamplesBài ...

Hướng dẫn javascript cơ bản (pdf)

Giáo trình Javascript Tiếng Việt cơ bản (PDF) | Javascript là một ngôn ngữ thông dịch (interpreter), chương trình nguồn của nó được nhúng (embedded) hoặc ...

Hướng dẫn scaler javascript

Bài viết này của Scaler Chủ đề bao gồm Kế thừa trong javascript, các ứng dụng của nó và cách sử dụng của nó trong lập trình thực & một số biệt ngữ ...

Căn bậc 2 trong javascript

Phương thức Math.sqrt() sẽ trả về căn bậc 2 của tham số được truyền vào.Bài viết này được đăng tại freetuts.net, không được copy dưới mọi hình ...

Hướng dẫn prototype in javascript

Đã đăng vào thg 5 20, 2017 2:23 CH 6 phút đọc Lời mở đầuVới mục đích của bài viết này, tôi sẽ nói về Javascript prototype trong ES5. Như mọi người đã ...

Hướng dẫn dùng asynchronis JavaScript

Mọi ngôn ngữ lập trình đều không hoàn hảo, nó sẽ luôn có những ưu và nhược điểm riêng. Javascript - một trong những ngôn ngữ lập trình phổ biến nhất ...

Hướng dẫn fetch api javascript

Nhóm phát triển của chúng tôi vừa ra mắt website langlearning.net học tiếng Anh, Nga, Đức, Pháp, Việt, Trung, Hàn, Nhật, ... miễn phí cho tất cả mọi người. Là ...

Hướng dẫn iterator javascript là gì

Nhóm phát triển của chúng tôi vừa ra mắt website langlearning.net học tiếng Anh, Nga, Đức, Pháp, Việt, Trung, Hàn, Nhật, ... miễn phí cho tất cả mọi người. Là ...

Hướng dẫn array reduce trong javascript

Trong bài này mình sẽ giới thiệu hàm array reduce trong javascript, đây là một method được thêm vào mảng kể từ phiên bản ES6.Bài viết này được đăng tại ...

Hướng dẫn dùng lemonkiwi JavaScript

Trước hết bạn cần hiểu cách thức hoạt động của mối nốiarray.splice (start [, deleteCount [, item1 [, item2 [, ...]]]])nó bắt đầu (chỉ mục bắt đầu từ 0), số ...

Hướng dẫn dùng x+2 JavaScript

JavaScript Operators được sử dụng để tính toán, so sánh các giá trị, biểu diễn các phép toán trong toán học, v...v. Và trong bài này mình sẽ cùng tìm hiểu một ...

Hướng dẫn map array object javascript

Trong bài này chúng ta sẽ tìm hiểu hàm map trong javascript, đây là hàm dùng để lặp qua các phần tử của mảng và cho phép xử lý giá trị của phần tử đó.Bài ...

Hướng dẫn javascript object spread

Spread syntax (...) allows an iterable, such as an array or string, to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected. In an ...

Hướng dẫn javascript reduce

Trong bài này mình sẽ giới thiệu hàm array reduce trong javascript, đây là một method được thêm vào mảng kể từ phiên bản ES6.Bài viết này được đăng tại ...

Hướng dẫn dùng jsphoto JavaScript

Vietnamese (Tiếng Việt) translation by Dai Phong (you can also view the original English article) Hình ảnh nổi tiếng là một trong những khía cạnh thách thức nhất của thiết ...

Javascript trong trình duyệt có thể làm gì

Để xem quảng cáo của Google trên trang web, hãy kích hoạt JavaScript trong trình duyệt của bạn.Kích hoạt JavaScript trong Google ChromeMở Chrome trên máy tính.Nhấp ...

Hướng dẫn dùng getpath JavaScript

Chào các bạn, như các bạn đã biết, một ứng dụng sẽ không chỉ đơn giản là hiển thị đoạn text ra màn hình như ứng dụng Hello World như chúng ta đã làm ở ...

Hướng dẫn this trong class javascript

Hôm nay mình sẽ giới thiệu với bạn về class trong JavaScript. Class được tạo ra như thế nào? Sử dụng class ra sao. Hãy theo dõi nhé! 1. Class là gì?Class có thể ...

Hướng dẫn dùng clickeme JavaScript

Hiện nay, JavaScript là một ngôn ngữ đang được nhiều bạn trẻ quan tâm nhiều trong những năm gần đây. Vậy JavaScript là gì? Và việc Tất cả sẽ có đầy ...