Skip to content

Commit

Permalink
feat(OCLT-29): add HMAC wrapper
Browse files Browse the repository at this point in the history
  • Loading branch information
ythepaut committed Apr 27, 2024
1 parent cf7ce57 commit f9b5eba
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 0 deletions.
1 change: 1 addition & 0 deletions build/exports.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ export { randomBytes } from "@occult-app/crypto/random";
export { sha256, sha512 } from "@occult-app/crypto/sha2";
export { kdf } from "@occult-app/crypto/kdf";
export { ppf } from "@occult-app/crypto/ppf";
export { hmac } from "@occult-app/crypto/hmac";
25 changes: 25 additions & 0 deletions src/hmac.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { subtle } from "crypto";
import { ByteArray } from "./types";

/**
* Computes the HMAC-SHA256 tag (hash) of the input data using the provided key.
*
* @param key The key used for HMAC computation.
* @param input The input data for which HMAC tag is computed.
* @returns The computed tag.
*/
async function hmac(key: ByteArray, input: ByteArray): Promise<ByteArray> {
const importedKey = await subtle.importKey(
"raw",
key,
{ name: "HMAC", hash: "SHA-256" },
false,
["sign"]
);

const tag = await subtle.sign("HMAC", importedKey, input);

return new Uint8Array(tag);
}

export { hmac };
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,4 @@ import { randomBytes } from "./random";
import { sha256, sha512 } from "./sha2";
import { kdf } from "./kdf";
import { ppf } from "./ppf";
import { hmac } from "./hmac";
17 changes: 17 additions & 0 deletions tests/hmac.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { ByteArray, bytesToHex, hexToBytes } from "../src/types";
import { hmac } from "../src/hmac";

describe("HMAC", () => {
it("should compute the HMAC-SHA256 hash", async () => {
const key: ByteArray = new Uint8Array([
108, 169, 151, 124, 154, 55, 16, 255, 152, 230, 112, 0, 136, 80, 171, 197, 35, 79, 55,
37, 161, 144, 41, 184, 148, 82, 137, 236, 132, 147, 213, 9
]);

const tag: ByteArray = await hmac(key, hexToBytes("deadbeef"));

expect(bytesToHex(tag)).toEqual(
"e17dec46db65352eb08841a383eaee78b234e3396fa035a5e2359abea0aa4d72"
);
});
});

0 comments on commit f9b5eba

Please sign in to comment.