Skip to content

Commit

Permalink
feat(node/crypto): add base64url encoding to hash.digest() (#2740)
Browse files Browse the repository at this point in the history
  • Loading branch information
dz4k committed Oct 3, 2022
1 parent 16ca2a1 commit 8d76f56
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
10 changes: 10 additions & 0 deletions node/crypto_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,16 @@ Deno.test("[node/crypto.Hash] basic usage - hex output", () => {
assertEquals(d, "1f8ac10f23c5b5bc1167bda84b833e5c057a77d2");
});

Deno.test("[node/crypto.Hash] basic usage - base64 output", () => {
const d = createHash("sha1").update("abc").update("def").digest("base64");
assertEquals(d, "H4rBDyPFtbwRZ72oS4M+XAV6d9I=");
});

Deno.test("[node/crypto.Hash] basic usage - base64url output", () => {
const d = createHash("sha1").update("abc").update("def").digest("base64url");
assertEquals(d, "H4rBDyPFtbwRZ72oS4M-XAV6d9I");
});

Deno.test("[node/crypto.Hash] streaming usage", async () => {
const source = Readable.from(["abc", "def"]);
const hash = createHash("sha1");
Expand Down
5 changes: 4 additions & 1 deletion node/internal/crypto/hash.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { Buffer } from "../../buffer.ts";
import { Transform } from "../../stream.ts";
import { encode as encodeToHex } from "../../../encoding/hex.ts";
import { encode as encodeToBase64 } from "../../../encoding/base64.ts";
import { encode as encodeToBase64Url } from "../../../encoding/base64url.ts";
import type { TransformOptions } from "../../_stream.d.ts";
import { validateString } from "../validators.mjs";
import { notImplemented } from "../../_utils.ts";
Expand Down Expand Up @@ -100,7 +101,7 @@ export class Hash extends Transform {
*
* If encoding is provided a string will be returned; otherwise a Buffer is returned.
*
* Supported encoding is currently 'hex', 'binary', 'base64'.
* Supported encodings are currently 'hex', 'binary', 'base64', 'base64url'.
*/
digest(encoding?: string): Buffer | string {
const digest = this.#context.digest(undefined);
Expand All @@ -115,6 +116,8 @@ export class Hash extends Transform {
return String.fromCharCode(...digest);
case "base64":
return encodeToBase64(digest);
case "base64url":
return encodeToBase64Url(digest);
default:
throw new Error(
`The output encoding for hash digest is not implemented: ${encoding}`,
Expand Down

0 comments on commit 8d76f56

Please sign in to comment.