-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
4 changed files
with
44 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 }; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" | ||
); | ||
}); | ||
}); |